package com.its.api.its.service.statistics;

import com.its.api.its.model.dto.statistics.FcltSttsStatErrorDto;
import com.its.api.its.model.dto.statistics.FcltSttsStatErrorInf;
import com.its.api.its.model.dto.statistics.FcltSttsStatTypeDto;
import com.its.api.its.repository.cctv.TbCctvSttsHsRepository;
import com.its.api.its.repository.vds.TbVdsCtlrSttsHsRepository;
import com.its.api.its.repository.vms.TbVmsSttsHsRepository;
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;

@Slf4j
@RequiredArgsConstructor
@Service
public class FcltSttsStatisticsService {

    private final TbCctvSttsHsRepository cctvSttsHsRepo;
    private final TbVmsSttsHsRepository vmsSttsHsRepo;
    private final TbVdsCtlrSttsHsRepository vdsSttsHsRepo;

    /**
     * 통계 - 시설물 통신단절 통계 - 시설물 구분 목록
     * @return
     */
    public List<FcltSttsStatTypeDto> findAllFcltSttsType() {

        List<FcltSttsStatTypeDto> result = new ArrayList<>();

        result.add(FcltSttsStatTypeDto.builder().fcltCd("CCTV").fcltNm("CCTV").build());
        result.add(FcltSttsStatTypeDto.builder().fcltCd("VMS").fcltNm("VMS").build());
        result.add(FcltSttsStatTypeDto.builder().fcltCd("VDS").fcltNm("VDS").build());

        return result;
    }

    public List<FcltSttsStatErrorDto> findAllStatisticsCommErrByDateRangeResult(List<FcltSttsStatErrorInf> data) {

        List<FcltSttsStatErrorDto> result = new ArrayList<>();
        data.forEach(obj -> {
            result.add(FcltSttsStatErrorDto.builder()
                    .fcltNmbr(obj.getFcltNmbr())
                    .fcltId(obj.getFcltId())
                    .fcltNm(obj.getFcltNm())
                    .totCnt(obj.getTotCnt().intValue())
                    .cms1Cnt(obj.getCms1Cnt().intValue())
                    .cms2Cnt(obj.getCms2Cnt().intValue())
                    .build());
        });
        return result;
    }

    @Transactional(readOnly = true)
    public List<FcltSttsStatErrorDto> findAllFcltStts(String fcltTypeCd, String fromDt, String toDt) {

        if (("CCTV").equalsIgnoreCase(fcltTypeCd)) {
            return findAllStatisticsCommErrByDateRangeResult(this.cctvSttsHsRepo.findAllStatisticsCommErrByDateRange(fromDt, toDt));
        }
        else
        if (("VMS").equalsIgnoreCase(fcltTypeCd)) {
            return findAllStatisticsCommErrByDateRangeResult(this.vmsSttsHsRepo.findAllStatisticsCommErrByDateRange(fromDt, toDt));
        }
        else
        if (("VDS").equalsIgnoreCase(fcltTypeCd)) {
            return findAllStatisticsCommErrByDateRangeResult(this.vdsSttsHsRepo.findAllStatisticsCommErrByDateRange(fromDt, toDt));
        }
        else {
            throw new NoSuchElementException("요청 파라미터가 잘못 됐습니다: " + fcltTypeCd);
        }
    }

}
