package com.its.api.utis.service;

import com.its.api.its.global.CodeManager;
import com.its.api.its.model.dto.common.FcltSttsDto;
import com.its.api.its.model.dto.common.FcltSttsListDto;
import com.its.api.its.model.dto.common.FcltSttsSummaryDto;
import com.its.api.its.model.dto.common.SttsCommErrDto;
import com.its.api.utis.model.dto.RsemstDto;
import com.its.api.utis.model.dto.UtisRseStateDto;
import com.its.api.utis.model.entity.Rsemst;
import com.its.api.utis.repository.RsemstRepository;
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 RsemstService {

    private final RsemstRepository repo;

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

    /**
     * 전체 데이터 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<RsemstDto> findAllList() {
        List<RsemstDto> result = new ArrayList<>();
        List<Rsemst> data = this.repo.findAllList();
        data.forEach(obj -> {
            result.add(obj.toDto());
        });
        return result;
    }

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

    /**
     * RSE 상태 통합
     * @return
     */
    @Transactional(readOnly = true)
    public FcltSttsSummaryDto findAllSttsSummary() {

        int total = this.repo.findAllListCount();
        int normal = this.repo.findAllListNormalCount();

        FcltSttsSummaryDto dto = FcltSttsSummaryDto.builder()
                .fcltType("RSE")
                .fcltNm("RSE")
                .totalCnt(total)
                .normalCnt(normal)
                .errorCnt(total - normal)
                .build();
        dto.init();
        return dto;
    }

    /**
     * RSE 개별 통신 상태 목록 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<FcltSttsDto> findAllListCommStts() {
        FcltSttsListDto result = findAllListSttsTotal();
        return result.getFcltList().get(0).getFcltObjs();
    }

    /**
     * 상태 목록
     * @param
     */
    public FcltSttsListDto findAllListSttsTotal() {
        FcltSttsListDto result = new FcltSttsListDto();
        AtomicInteger error = new AtomicInteger();
        AtomicInteger normal = new AtomicInteger();
        String fcltType = "RSE";

        error.set(0);
        normal.set(0);
        List<FcltSttsDto> sttsDtoList = new ArrayList<>();
        List<Rsemst> ctlrList = this.repo.findAllList();
        ctlrList.forEach(obj -> {
            UtisRseStateDto.RseCommSttsDto dto = UtisRseStateDto.toSttsDto(obj);
            FcltSttsDto stts = FcltSttsDto.builder()
                    .fcltType(fcltType)
                    .fcltNmbr(obj.getRseid())
                    .fcltId(obj.getRseid())
                    .fcltNm(obj.getLocation())
                    .fcltKind("1")
                    .xCrdn(obj.getCoordx()/10000000.)
                    .yCrdn(obj.getCoordy()/10000000.)
                    .sttsCd(dto.getCommCd())
                    .sttsDesc(dto.getCommDesc())
                    .updtDt(dto.getCollDt())
                    .build();

            sttsDtoList.add(stts);

            if (CodeManager.CMNC_STTS_NORMAL.equals(dto.getCommCd())) {
                normal.getAndIncrement();
            }
            else {
                error.getAndIncrement();
            }
        });

        FcltSttsSummaryDto cntCctv = FcltSttsSummaryDto.builder()
                .fcltType(fcltType)
                .fcltNm(fcltType)
                .totalCnt(ctlrList.size())
                .normalCnt(normal.get())
                .errorCnt(error.get())
                .colErrCnt(0)
                .build();
        cntCctv.setFcltObjs(sttsDtoList);
        result.getFcltList().add(cntCctv);

        return result;
    }

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

        Map<String, SttsCommErrDto> result = new HashMap<>();
        List<Rsemst> ctlrList = this.repo.findAllList();
        ctlrList.forEach(obj -> {
            UtisRseStateDto.RseCommSttsDto dto = UtisRseStateDto.toSttsDto(obj);
            if (!CodeManager.CMNC_STTS_NORMAL.equals(dto.getCommCd())) {
                SttsCommErrDto commErrorDto = new SttsCommErrDto();
                commErrorDto.setCtlrNmbr(obj.getRseid());
                commErrorDto.setCtlrId(obj.getRseid());
                commErrorDto.setCtlrNm(obj.getLocation());
                commErrorDto.setUpdtDt(dto.getCollDt());
                commErrorDto.setCommCd(dto.getCommCd());
                commErrorDto.setCommDesc(CodeManager.getCodeDescShort(CodeManager.CMNC_STTS_CD, commErrorDto.getCommCd()));
                commErrorDto.setCommErrCnt(0);
                commErrorDto.setColCnt(0);
                result.put(commErrorDto.getCtlrNmbr(), commErrorDto);
            }
        });

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