package com.its.op.service.its.analysis;

import com.its.op.global.CodeManager;
import com.its.op.dto.its.analysis.PtrnDataDto;
import com.its.op.dto.its.analysis.PtrnDataParam;
import com.its.op.dto.its.code.TbCmmnCdDto;
import com.its.op.dao.mapper.its.analysis.PtrnDataMapper;
import com.its.op.service.its.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) throws NoSuchElementException {

        if ("LINK".equalsIgnoreCase(cond.getPTRN_TYPE())) {
            if ("5M".equalsIgnoreCase(cond.getPTRN_DATA())) {
                cond.setTABLE_NAME("TB_LINK_PTRN_5M");
            }
            else {
                cond.setTABLE_NAME("TB_LINK_PTRN_15M");
            }
            return this.mapper.findAllByDateRangeLINK(cond);
        }
        else if ("IFSC".equalsIgnoreCase(cond.getPTRN_TYPE())) {
            if ("5M".equalsIgnoreCase(cond.getPTRN_DATA())) {
                cond.setTABLE_NAME("TB_IFSC_PTRN_5M");
            }
            else {
                cond.setTABLE_NAME("TB_IFSC_PTRN_15M");
            }
            return this.mapper.findAllByDateRangeIFSC(cond);
        }
        else if ("ROAD".equalsIgnoreCase(cond.getPTRN_TYPE())) {
            if ("5M".equalsIgnoreCase(cond.getPTRN_DATA())) {
                cond.setTABLE_NAME("TB_ROAD_PTRN_5M");
            }
            else {
                cond.setTABLE_NAME("TB_ROAD_PTRN_15M");
            }
            return this.mapper.findAllByDateRangeROAD(cond);
        }
        else {
            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;
    }

}
