package com.its.op.service.its.facility;

import com.its.op.dao.repository.its.code.TbCmmnCdRepository;
import com.its.op.dao.repository.its.facility.TbFcltInfrRepository;
import com.its.op.dto.its.cctv.TbCctvCtlrDto;
import com.its.op.dto.its.common.NewIdLongDto;
import com.its.op.dto.its.facility.FcltWorkStepDto;
import com.its.op.dto.its.facility.TbFcltInfrDto;
import com.its.op.dto.its.facility.UnRegisteredFcltInfrDto;
import com.its.op.dto.its.vds.TbVdsCtlrDto;
import com.its.op.dto.its.vms.TbVmsCtlrDto;
import com.its.op.entity.its.code.TbCmmnCd;
import com.its.op.entity.its.facility.TbFcltInfr;
import com.its.op.global.CodeManager;
import com.its.op.service.its.cctv.TbCctvCtlrService;
import com.its.op.service.its.vds.TbVdsCtlrService;
import com.its.op.service.its.vms.TbVmsCtlrService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbFcltInfrService {

    private final TbFcltInfrRepository repo;
    private final TbVmsCtlrService vmsCtlrService;
    private final TbVdsCtlrService vdsCtlrService;
    private final TbCctvCtlrService cctvCtlrService;
    private final TbCmmnCdRepository cmmnCdRepo;

    // 데이터 1건 조회, 없으면 exception
    private TbFcltInfr requireOne(Long id) throws NoSuchElementException {
        Optional<TbFcltInfr> info = this.repo.findById(id);
        if (info.isPresent()) {
            return info.get();
        }
        else {
            throw new NoSuchElementException("데이터가 존재하지 않습니다: " + id);
        }
    }

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

    /**
     * 삭제되지 않은 시설물 정보 전체 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbFcltInfrDto> findAllList(String fcltType) {
        List<TbFcltInfrDto> result = new ArrayList<>();
        List<TbFcltInfr> data;
        if (fcltType == null || fcltType.isEmpty()) {
            data = this.repo.findAllList();
        }
        else {
            data = this.repo.findAllByFcltType(fcltType);
        }
        data.forEach(obj -> {
            result.add(obj.toDto());
        });
        return result;
    }

    // 데이터 1건 조회(기존 데이터가 반드시 존재해야 함)
    @Transactional(readOnly = true)
    public TbFcltInfrDto findById(Long id) {
        TbFcltInfr entity = requireOne(id);
        return entity.toDto();
    }

    // 데이터 변경
    @Transactional
    public TbFcltInfrDto updateById(Long id, TbFcltInfrDto.TbFcltInfrUpdReq req) {
        TbFcltInfr entity = requireOne(id);
        entity.updateInfo(req);
        this.repo.save(entity);
        return entity.toDto();
    }

    // 데이터 변경 또는 생성-목록(데이터가 존재하면 업데이트 없으면 신규로 생성)
    @Transactional
    public List<TbFcltInfrDto> mergeInfoList(List<TbFcltInfrDto.TbFcltInfrUpdReq> reqList) {
        List<TbFcltInfrDto> result = new ArrayList<>();
        for (TbFcltInfrDto.TbFcltInfrUpdReq req : reqList) {
            TbFcltInfr obj = req.toEntity();
            this.repo.save(obj);
            result.add(obj.toDto());
        }
        return result;
    }

    // 데이터 변경 또는 생성-개별(데이터가 존재하면 업데이트 없으면 신규로 생성)
    @Transactional
    public TbFcltInfrDto mergeInfo(TbFcltInfrDto.TbFcltInfrUpdReq req) {
        TbFcltInfr obj = req.toEntity();
        this.repo.save(obj);
        return obj.toDto();
    }

    // 정보 삭제-개별, 데이터 존재하지 않으면 Exception
    @Transactional
    public TbFcltInfrDto deleteById(Long id) {
        TbFcltInfr entity = requireOne(id);
        this.repo.deleteById(id);
        return entity.toDto();
    }

    // 정보 삭제-목록, 존재하는 데이터 만 삭제
    @Transactional
    public List<TbFcltInfrDto> deleteByIds(List<Long> ids) {
        List<TbFcltInfrDto> result = new ArrayList<>();
        for (Long id : ids) {
            Optional<TbFcltInfr> obj = this.repo.findById(id);
            if (obj.isPresent()) {
                this.repo.deleteById(id);
                result.add(obj.get().toDto());
            }
        }
        return result;
    }

    /**
     * 미등록 시설물 정보 등록
     * @param listReq
     * @return
     */
    @Transactional
    public List<TbFcltInfrDto> mergeRegInfoList(List<UnRegisteredFcltInfrDto.TbRegFcltInfrUpdReq> listReq) {
        NewIdLongDto fcltNmbrDto = getNewNmbr();
        Long fcltNmbr = fcltNmbrDto.getNewId();
        List<TbFcltInfrDto> result = new ArrayList<>();
        for (UnRegisteredFcltInfrDto.TbRegFcltInfrUpdReq obj : listReq) {
            TbFcltInfr entity = obj.toEntity(fcltNmbr++);
            this.repo.save(entity);
            result.add(entity.toDto());
        }
        return result;
    }

    /**
     * 미등록 시설물 정보 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<UnRegisteredFcltInfrDto> findAllUnRegisteredList(String fcltType) {
        List<UnRegisteredFcltInfrDto> result = new ArrayList<>();
        Map<String, TbFcltInfrDto> regMap = new HashMap<>();
        List<TbFcltInfrDto> regList = findAllList(fcltType);
        regList.forEach(obj -> {
            regMap.put(obj.getFcltId(), obj);
        });

        if (fcltType == null || "VMS".equals(fcltType)) {
            List<TbVmsCtlrDto> vmsList = this.vmsCtlrService.findAllList();
            vmsList.forEach(obj -> {
                TbFcltInfrDto regObj = regMap.get(obj.getVmsCtlrId());
                if (regObj == null) {
                    result.add(UnRegisteredFcltInfrDto.builder()
                            .fcltType("VMS")
                            .fcltId(obj.getVmsCtlrId())
                            .fcltLctn(obj.getVmsNm())
                            .build());
                }
            });
        }

        if (fcltType == null || "VDS".equals(fcltType)) {
            List<TbVdsCtlrDto> vdsList = this.vdsCtlrService.findAllList();
            vdsList.forEach(obj -> {
                TbFcltInfrDto regObj = regMap.get(obj.getVdsCtlrId());
                if (regObj == null) {
                    result.add(UnRegisteredFcltInfrDto.builder()
                            .fcltType("VDS")
                            .fcltId(obj.getVdsCtlrId())
                            .fcltLctn(obj.getVdsNm())
                            .build());
                }
            });
        }

        if (fcltType == null || "CCTV".equals(fcltType)) {
            List<TbCctvCtlrDto> cctvList = this.cctvCtlrService.findAllList();
            cctvList.forEach(obj -> {
                TbFcltInfrDto regObj = regMap.get(obj.getCctvCtlrId());
                if (regObj == null) {
                    result.add(UnRegisteredFcltInfrDto.builder()
                            .fcltType("CCTV")
                            .fcltId(obj.getCctvCtlrId())
                            .fcltLctn(obj.getIstlLctnNm())
                            .build());
                }
            });
        }

        //TODO: DSRC, SIG, 스마트교차로
        return result;
    }

    /**
     * 사업단계 코드 목록 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<FcltWorkStepDto> findAllWorkStep() {
        List<FcltWorkStepDto> result = new ArrayList<>();
        List<TbCmmnCd> data = this.cmmnCdRepo.findAllByCmmnClsfCd(CodeManager.FMS_FSTEP);
        if (data != null) {
            data.forEach(obj -> {
                if (("Y").equals(obj.getUseYn())) {
                    result.add(FcltWorkStepDto.makeDto(obj));
                }
            });
        }
        return result;
    }
    @Transactional(readOnly = true)
    public NewIdLongDto getNewNmbr() {
        Long newId = this.repo.getNewNmbr();
        return NewIdLongDto.builder().newId(newId).build();
    }

}
