package com.its.api.its.service.cctv;

import com.its.api.its.global.CodeManager;
import com.its.api.its.model.dto.cctv.TbCctvCtlrDto;
import com.its.api.its.model.dto.cctv.TbCctvSttsDto;
import com.its.api.its.model.dto.common.*;
import com.its.api.its.model.entity.cctv.TbCctvCtlr;
import com.its.api.its.repository.cctv.TbCctvCtlrRepository;
import com.its.api.its.repository.cctv.TbCctvSttsHsRepository;
import com.its.api.utils.ItsUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbCctvCtlrService {

    private final TbCctvCtlrRepository repo;
    private final TbCctvSttsHsRepository sttsHsRepo;

    // 데이터 1건 조회, 없으면 exception
    private TbCctvCtlr requireOne(Long id) {
        return this.repo.findById(id)
                .orElseThrow(() -> new NoSuchElementException("데이터가 존재하지 않습니다: " + id));
    }

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

    /**
     * 삭제 되지 않은 제어기 정보 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbCctvCtlrDto> findAllList() {
        List<TbCctvCtlrDto> result = new ArrayList<>();
        List<TbCctvCtlr> data = this.repo.findAllList();
        for (TbCctvCtlr entity : data) {
            if (("N").equals(entity.getDelYn())) {
                result.add(entity.toDto());
            }
        }
        return result;
    }


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

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

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

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

    /**
     * 통신이상 시설물 정보 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<SttsCommErrDto> findAllListCommError() {

        Map<String, SttsCommErrDto> result = new HashMap<>();
        List<TbCctvCtlr> data = this.repo.findAllList();
        List<SttsHsErrCntInf> errList = this.sttsHsRepo.findAllCommErrorCount(ItsUtils.getFromToday());

        // 통신 상태가 오류 인 제어기 정보만 조회한다.
        data.forEach(obj -> {
            TbCctvSttsDto dto = obj.toSttsDto();
            if (!CodeManager.CMNC_STTS_NORMAL.equals(dto.getCmncSttsCd())) {
                SttsCommErrDto commErrorDto = new SttsCommErrDto();
                commErrorDto.setCtlrNmbr(String.valueOf(dto.getCctvMngmNmbr()));
                commErrorDto.setCtlrId(dto.getCctvCtlrId());
                commErrorDto.setCtlrNm(dto.getIstlLctnNm());
                commErrorDto.setUpdtDt(dto.getUpdtDt());
                commErrorDto.setCommCd(dto.getCmncSttsCd());
                commErrorDto.setCommDesc(CodeManager.getCodeDescShort(CodeManager.CMNC_STTS_CD, commErrorDto.getCommCd()));
                commErrorDto.setCommErrCnt(0);
                commErrorDto.setColCnt(0);
                result.put(commErrorDto.getCtlrNmbr(), commErrorDto);
            }
        });

        // 오늘 00:00:00 이후 발생한 오류 건수를 업데이트
        errList.forEach(obj -> {
            SttsCommErrDto dto = result.get(obj.getNmbr());
            if (dto != null) {
                dto.setCommErrCnt(obj.getErrCnt().intValue());
            }
        });

        return new ArrayList<>(result.values());
    }

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

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

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

        List<FcltSttsDto> sttsDtoList = new ArrayList<>();
        List<TbCctvCtlr> ctlrList = this.repo.findAllList();
        ctlrList.forEach(obj -> {
            TbCctvSttsDto dto = obj.toSttsDto();
            FcltSttsDto stts = FcltSttsDto.builder()
                    .fcltType(fcltType)
                    .fcltNmbr(String.valueOf(obj.getCctvMngmNmbr()))
                    .fcltId(obj.getCctvCtlrId())
                    .fcltNm(obj.getIstlLctnNm())
                    .fcltKind(obj.getCctvType())
                    .xCrdn(obj.getXCrdn())
                    .yCrdn(obj.getYCrdn())
                    .strmUrl(obj.getStrmSesnNm())
                    .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();
        summaryDto.setFcltObjs(sttsDtoList);

        result.getFcltList().add(summaryDto);

        return result;
    }

}
