package com.its.api.its.service.link;

import com.its.api.its.model.dto.analysis.TbTrfcPrcnStatDto;
import com.its.api.its.model.dto.analysis.TbTrfcPrcnStatInf;
import com.its.api.its.repository.ifsc.TbIfscRepository;
import com.its.api.its.repository.link.TbLinkRepository;
import com.its.api.its.repository.link.TbTrfcPrcnStatRepository;
import com.its.api.its.repository.road.TbRoadRepository;
import com.its.api.its.repository.vms.TbVmsIfscRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

@Slf4j
@RequiredArgsConstructor
@Service
public class TbTrfcPrcnStatService {

    private final TbTrfcPrcnStatRepository 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<TbTrfcPrcnStatInf> 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 {
            throw new NoSuchElementException("요청 파라미터가 잘못 됐습니다: " + OFFR_TYPE);
        }

        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;
    }

}
