package com.its.api.its.service.analysis;

import com.its.api.its.global.CodeManager;
import com.its.api.its.model.dto.analysis.PtrnDataDto;
import com.its.api.its.model.dto.analysis.PtrnDataParam;
import com.its.api.its.model.dto.code.TbCmmnCdDto;
import com.its.api.its.repository.analysis.PtrnDataMapper;
import com.its.api.its.service.code.TbCmmnCdService;
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 PtrnDataService {

    private final PtrnDataMapper mapper;
    private final TbCmmnCdService cmmnCdService;

    public List<PtrnDataDto> findAllByDateRange(PtrnDataParam cond) {

        if ("LINK".equalsIgnoreCase(cond.getPTRN_TYPE())) {
            if ("5M".equalsIgnoreCase(cond.getPTRN_DATA())) {
                cond.setTABLE_NAME("TB_LINK_5M_PTRN");
            }
            else {
                cond.setTABLE_NAME("TB_LINK_15M_PTRN");
            }
            return this.mapper.findAllByDateRangeLINK(cond);
        }
        else if ("IFSC".equalsIgnoreCase(cond.getPTRN_TYPE())) {
            if ("5M".equalsIgnoreCase(cond.getPTRN_DATA())) {
                cond.setTABLE_NAME("TB_IFSC_5M_PTRN");
            }
            else {
                cond.setTABLE_NAME("TB_IFSC_15M_PTRN");
            }
            return this.mapper.findAllByDateRangeIFSC(cond);
        }
        else if ("ROAD".equalsIgnoreCase(cond.getPTRN_TYPE())) {
            if ("5M".equalsIgnoreCase(cond.getPTRN_DATA())) {
                cond.setTABLE_NAME("TB_ROAD_5M_PTRN");
            }
            else {
                cond.setTABLE_NAME("TB_ROAD_15M_PTRN");
            }
            return this.mapper.findAllByDateRangeROAD(cond);
        }

        throw new NoSuchElementException("요청 파라미터가 잘못 됐습니다: " + cond.toString());
    }

    // 패턴 요일 유형 코드 목록 조회
    @Transactional(readOnly = true)
    public List<PtrnDataDto.PtrnDataDayType> findAllDayType() {
        List<PtrnDataDto.PtrnDataDayType> result = new ArrayList<>();
        //TbCmmnCdDto allEntity = TbCmmnCdDto.builder().cmmnCd("ALL").cmmnCdKorNm("전체").build();
        //PtrnDataDto.PtrnDataDayType all = new PtrnDataDto.PtrnDataDayType(allEntity);
        //result.add(all);

        List<TbCmmnCdDto> data = this.cmmnCdService.findAllByCmmnClsfCd(CodeManager.DAY_TYPE_CD);
        if (data != null) {
	        data.forEach(obj -> {
	            if (("Y").equals(obj.getUseYn())) {
	                result.add(new PtrnDataDto.PtrnDataDayType(obj));
	            }
	        });
	    }
        return result;
    }

}
