package com.its.op.service.its.link;

import com.its.op.dao.repository.its.ifsc.TbIfscRepository;
import com.its.op.dao.repository.its.link.TbLinkRepository;
import com.its.op.dao.repository.its.link.TbTrafPrcnStatRepository;
import com.its.op.dao.repository.its.road.TbRoadRepository;
import com.its.op.dao.repository.its.vms.TbVmsIfscRepository;
import com.its.op.dto.its.analysis.TbTrfcPrcnStatDto;
import com.its.op.dto.its.analysis.TbTrafPrcnStatInf;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbTrafPrcnStatService {

    private final TbTrafPrcnStatRepository repo;
    private final TbLinkRepository linkRepo;
    private final TbIfscRepository ifscRepo;
    private final TbRoadRepository roadRepo;
    private final TbVmsIfscRepository vmsIfscRepo;

    /**
     * 교통정보 제공결과 분석 조회
     * @param OFFR_TYPE
     * @param fromDt
     * @param toDt
     * @return
     */
    public List<TbTrfcPrcnStatDto> findAllByDateRange(String OFFR_TYPE, String fromDt, String toDt) {

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

        int totCnt = 0;
        List<TbTrafPrcnStatInf> data = null;

        if (("LINK").equalsIgnoreCase(OFFR_TYPE)) {
            totCnt = this.linkRepo.findAllCount();
            data = this.repo.findAllByDateRangeLINK(fromDt, toDt);
        }
        else if (("IFSC").equalsIgnoreCase(OFFR_TYPE)) {
            totCnt = this.ifscRepo.findAllCount();
            data = this.repo.findAllByDateRangeIFSC(fromDt, toDt);
        }
        else if (("ROAD").equalsIgnoreCase(OFFR_TYPE)) {
            totCnt = this.roadRepo.findAllCount();
            data = this.repo.findAllByDateRangeROAD(fromDt, toDt);
        }
        else if (("VMS").equalsIgnoreCase(OFFR_TYPE)) {
            totCnt = this.vmsIfscRepo.findAllCount();
            data = this.repo.findAllByDateRangeVMS(fromDt, toDt);
        }
        else {
            return result;
        }

        if (data != null) {
            int finalTotCnt = totCnt;
            data.forEach(obj -> {
                TbTrfcPrcnStatDto dto = TbTrfcPrcnStatDto.builder()
                        .prcnDt(obj.getPrcnDt())
                        .totCnt(finalTotCnt)
                        .ltc1Cnt(obj.getLigtNum().intValue())
                        .ltc2Cnt(obj.getDelyNum().intValue())
                        .ltc3Cnt(obj.getCngsNum().intValue())
                        .build();

                dto.makeOffrCnt();
                result.add(dto);
            });
        }
        return result;
    }

}
