package com.its.op.service.its.road;

import com.its.op.dao.repository.its.road.TbRoad15mStatRepository;
import com.its.op.dto.its.analysis.TbTrafStat15mCountDto;
import com.its.op.dto.its.analysis.TbTrafStat15mCountInf;
import com.its.op.dto.its.analysis.TbTrafStat15mListDto;
import com.its.op.dto.its.analysis.TbTrafStat15mListInf;
import com.its.op.dto.its.road.TbRoadStat15mDto;
import com.its.op.entity.its.road.TbRoadStat15m;
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;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbRoad15mStatService {

    private final TbRoad15mStatRepository repo;

    // 전체 데이터 조회
    @Transactional(readOnly = true)
    public List<TbRoadStat15mDto> findAll() {
        List<TbRoadStat15mDto> result = new ArrayList<>();
        List<TbRoadStat15m> data = this.repo.findAll();
        for (TbRoadStat15m entity : data) {
            result.add(entity.toDto());
        }
        return result;
    }

    /**
     * 통계/분석: 소통정보 이력분석-데이터 건수 조회
     * @param fromDt
     * @param toDt
     * @return
     */
    public List<TbTrafStat15mCountDto> findAllCountByDateRange(String fromDt, String toDt) {

        List<TbTrafStat15mCountDto> result = new ArrayList<>();
        List<TbTrafStat15mCountInf> data = this.repo.findAllCountByDateRange(fromDt, toDt);
        if (data != null) {
            data.forEach(obj -> {
                result.add(TbTrafStat15mCountDto.builder()
                        .statDt(obj.getStatDt())
                        .dataCnt(obj.getDataCnt().intValue())
                        .build());
            });
        }
        return result;
    }

    /**
     * 통계/분석: 소통정보 이력분석-이력 데이터 조회
     * @param statDt
     * @return
     */
    public List<TbTrafStat15mListDto> findAllDataByDateRange(String statDt) {

        List<TbTrafStat15mListDto> result = new ArrayList<>();
        List<TbTrafStat15mListInf> data = this.repo.findAllDataByDateRange(statDt);
        if (data != null) {
            data.forEach(obj -> {
                result.add(TbTrafStat15mListDto.builder()
                        .id(obj.getId().longValue())
                        .cmtrGradCd(obj.getCmtrGradCd())
                        .sped(obj.getSped().intValue())
                        .build());
            });
        }
        return result;
    }
}
