package com.its.op.service.its.cctv;

import com.its.op.dao.repository.its.cctv.TbCctvCtlrRepository;
import com.its.op.dao.repository.its.cctv.TbCctvCtlrSttsHsRepository;
import com.its.op.dto.its.cctv.TbCctvCtlrDto;
import com.its.op.dto.its.cctv.TbCctvCtlrSttsDto;
import com.its.op.dto.its.common.*;
import com.its.op.entity.its.cctv.TbCctvCtlr;
import com.its.op.global.CodeManager;
import com.its.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 TbCctvCtlrSttsHsRepository sttsHsRepo;

    // 데이터 1건 조회, 없으면 exception
    private TbCctvCtlr requireOne(Long id) throws NoSuchElementException {
        Optional<TbCctvCtlr> info = this.repo.findById(id);
        if (info.isPresent()) {
            return info.get();
        }
        else {
            throw new NoSuchElementException("데이터가 존재하지 않습니다: " + id);
        }
//        return 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();
        data.forEach(obj -> {
            //if (("N").equals(entity.getDelYn())) {
            result.add(obj.toDto());
            //}
        });
        return result;
    }


    /**
     * 삭제 되지 않은 제어기 상태 정보 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbCctvCtlrSttsDto> findAllStts() {
        List<TbCctvCtlrSttsDto> 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);
        entity.setDelete();
        //this.repo.deleteById(id);
        this.repo.save(entity);
        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 -> {
            TbCctvCtlrSttsDto dto = obj.toSttsDto();
            if (!CodeManager.CMNC_STTS_NORMAL.equals(dto.getCmncSttsCd())) {
                SttsCommErrDto commErrorDto = new SttsCommErrDto();
                commErrorDto.setCtlrNmbr(String.valueOf(dto.getCctvCtlrNmbr()));
                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(boolean total) {

        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 -> {
            TbCctvCtlrSttsDto dto = obj.toSttsDto();
            if (total) {
                FcltSttsDto stts = FcltSttsDto.builder()
                        .fcltType(fcltType)
                        .fcltNmbr(String.valueOf(obj.getCctvCtlrNmbr()))
                        .fcltId(obj.getCctvCtlrId())
                        .fcltNm(obj.getIstlLctnNm())
                        .fcltKind(obj.getCctvTypeCd())
                        .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();
        if (total) {
            summaryDto.setFcltObjs(sttsDtoList);
        }
        result.getFcltList().add(summaryDto);

        return result;
    }

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