package com.its.op.service.its.rse;

import com.its.op.dao.repository.its.rse.TbRseCtlrRepository;
import com.its.op.dto.its.common.FcltSttsDto;
import com.its.op.dto.its.common.FcltSttsListDto;
import com.its.op.dto.its.common.FcltSttsSummaryDto;
import com.its.op.dto.its.common.NewIdLongDto;
import com.its.op.dto.its.rse.TbRseCtlrDto;
import com.its.op.dto.its.rse.TbRseCtlrSttsDto;
import com.its.op.entity.its.rse.TbRseCtlr;
import com.its.op.global.CodeManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbRseCtlrService {

    private final TbRseCtlrRepository repo;

    // 데이터 1건 조회, 없으면 exception
    private TbRseCtlr requireOne(Long id) throws NoSuchElementException {
        Optional<TbRseCtlr> info = this.repo.findById(id);
        if (info.isPresent()) {
            return info.get();
        }
        else {
            throw new NoSuchElementException("데이터가 존재하지 않습니다: " + id);
        }
//        return this.repo.findById(id)
//                .orElseThrow(() -> new NoSuchElementException("데이터가 존재하지 않습니다: " + id));
    }

    // 전체 데이터 조회
    @Transactional(readOnly = true)
    public List<TbRseCtlrDto> findAll() {
        List<TbRseCtlrDto> result = new ArrayList<>();
        List<TbRseCtlr> data = this.repo.findAll();
        for (TbRseCtlr entity : data) {
            result.add(entity.toDto());
        }
        return result;
    }

    // 데이터 1건 조회(기존 데이터가 반드시 존재해야 함)
    @Transactional(readOnly = true)
    public TbRseCtlrDto findById(Long id) {
        TbRseCtlr entity = requireOne(id);
        return entity.toDto();
    }

    // 데이터 변경
    @Transactional
    public TbRseCtlrDto updateById(Long id, TbRseCtlrDto.TbRseCtlrUpdReq req) {
        TbRseCtlr entity = requireOne(id);
        entity.updateInfo(req);
        this.repo.save(entity);
        return entity.toDto();
    }

    // 데이터 변경 또는 생성-목록(데이터가 존재하면 업데이트 없으면 신규로 생성)
    @Transactional
    public List<TbRseCtlrDto> mergeInfoList(List<TbRseCtlrDto.TbRseCtlrUpdReq> reqList) {
        List<TbRseCtlrDto> result = new ArrayList<>();
        for (TbRseCtlrDto.TbRseCtlrUpdReq req : reqList) {
            TbRseCtlr obj = req.toEntity();
            this.repo.save(obj);
            result.add(obj.toDto());
        }
        return result;
    }

    // 데이터 변경 또는 생성-개별(데이터가 존재하면 업데이트 없으면 신규로 생성)
    @Transactional
    public TbRseCtlrDto mergeInfo(TbRseCtlrDto.TbRseCtlrUpdReq req) {
        TbRseCtlr obj = req.toEntity();
        this.repo.save(obj);
        return obj.toDto();
    }

    // 정보 삭제-개별, 데이터 존재하지 않으면 Exception
    @Transactional
    public TbRseCtlrDto deleteById(Long id) {
        TbRseCtlr entity = requireOne(id);
        this.repo.deleteById(id);
        return entity.toDto();
    }

    // 정보 삭제-목록, 존재하는 데이터 만 삭제
    @Transactional
    public List<TbRseCtlrDto> deleteByIds(List<Long> ids) {
        List<TbRseCtlrDto> result = new ArrayList<>();
        for (Long id : ids) {
            Optional<TbRseCtlr> obj = this.repo.findById(id);
            if (obj.isPresent()) {
                this.repo.deleteById(id);
                result.add(obj.get().toDto());
            }
        }
        return result;
    }

    /**
     * 신규 제어기 번호 조회
     * @return
     */
    @Transactional(readOnly = true)
    public NewIdLongDto getNewNmbr() {
        Long newId = this.repo.getNewNmbr();
        return NewIdLongDto.builder().newId(newId).build();
    }

    //@Transactional
    public Integer updateClctAbnrBasi(Integer clctAbnrBasi) {
        return this.repo.updateClctAbnrBasi(clctAbnrBasi);
    }

    /**
     * 상태 목록
     * @param
     */
    @Transactional(readOnly = true)
    public FcltSttsListDto findAllSttsListTotal(boolean total) {

        String fcltType = "DSRC";
        FcltSttsListDto result = new FcltSttsListDto();

        AtomicInteger error = new AtomicInteger(0);
        AtomicInteger normal = new AtomicInteger(0);

        List<FcltSttsDto> sttsDtoList = new ArrayList<>();
        List<TbRseCtlr> ctlrList = this.repo.findAllList();
        ctlrList.forEach(obj -> {
            TbRseCtlrSttsDto dto = obj.toSttsDto();
            if (total) {
                FcltSttsDto stts = FcltSttsDto.builder()
                        .fcltType(fcltType)
                        .fcltNmbr(String.valueOf(obj.getRseCtlrNmbr()))
                        .fcltId(obj.getRseCtlrId())
                        .fcltNm(obj.getIstlLctnNm())
                        .fcltKind(obj.getRseTypeCd())
                        .xCrdn(obj.getXCrdn())
                        .yCrdn(obj.getYCrdn())
                        .strmUrl("")
                        .sttsCd(dto.getCmncSttsCd())
                        .sttsDesc(dto.getCmncSttsDesc())
                        .build();

                sttsDtoList.add(stts);
            }
            if (CodeManager.CMNC_STTS_NORMAL.equals(dto.getCmncSttsCd())) {
                normal.getAndIncrement();
            }
            else {
                error.getAndIncrement();
            }
        });

        FcltSttsSummaryDto summaryDto = FcltSttsSummaryDto.builder()
                .fcltType(fcltType)
                .fcltNm(fcltType)
                .totalCnt(ctlrList.size())
                .normalCnt(normal.get())
                .errorCnt(error.get())
                .colErrCnt(0)
                .build();

        summaryDto.init();
        if (total) {
            summaryDto.setFcltObjs(sttsDtoList);
        }
        result.getFcltList().add(summaryDto);

        return result;
    }

    /**
     * 삭제 되지 않은 제어기 상태 정보 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbRseCtlrSttsDto> findAllStts() {
        List<TbRseCtlrSttsDto> result = new ArrayList<>();
        List<TbRseCtlr> data = this.repo.findAllList();
        data.forEach(obj -> {
            result.add(obj.toSttsDto());
        });
        return result;
    }

}
