package com.its.op.service.its.scrs;

import com.its.op.dao.repository.its.scrs.TbScSgnlCtlrRepository;
import com.its.op.dto.its.common.FcltSttsDto;
import com.its.op.dto.its.common.FcltSttsListDto;
import com.its.op.dto.its.common.FcltSttsSummaryDto;
import com.its.op.dto.its.scrs.TbScSgnlCtlrDto;
import com.its.op.dto.its.scrs.TbScSgnlCtlrPhaseDto;
import com.its.op.dto.its.scrs.TbScSgnlIxrSttsDto;
import com.its.op.entity.its.scrs.TbScSgnlCtlr;
import com.its.op.global.CodeManager;
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;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbScSgnlCtlrService {

    private final TbScSgnlCtlrRepository repo;

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

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

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

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

    // 데이터 변경
    @Transactional
    public TbScSgnlCtlrDto updateById(Integer sgnlIxrNmbr, TbScSgnlCtlrDto.TbScSgnlCtlrUpdReq req) {
        TbScSgnlCtlr entity = requireOne(sgnlIxrNmbr);
        entity.updateInfo(req);
        this.repo.save(entity);
        return entity.toDto();
    }

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

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

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

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

    /**
     * 신호현시정보 전체조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbScSgnlCtlrPhaseDto> findAllPhaseList() {
        List<TbScSgnlCtlrPhaseDto> result = new ArrayList<>();
        List<TbScSgnlCtlr> data = this.repo.findAllList();
        for (TbScSgnlCtlr entity : data) {
            result.add(entity.toPhaseDto());
        }
        return result;
    }

    /**
     * 신호현시정보 개별조회
     * @param sgnlIxrNmbr
     * @return
     */
    @Transactional(readOnly = true)
    public TbScSgnlCtlrPhaseDto findByIdPhase(Integer sgnlIxrNmbr) {
        TbScSgnlCtlr entity = requireOne(sgnlIxrNmbr);
        return entity.toPhaseDto();
    }

    /**
     * 상태 목록
     * @param
     */
    @Transactional(readOnly = true)
    public FcltSttsListDto findAllSttsListTotal(boolean total) {

        String fcltType = "SIG";
        FcltSttsListDto result = new FcltSttsListDto();

        AtomicInteger error = new AtomicInteger(0);
        AtomicInteger normal = new AtomicInteger(0);

        List<FcltSttsDto> sttsDtoList = new ArrayList<>();
        List<TbScSgnlCtlr> ctlrList = this.repo.findAllList();
        ctlrList.forEach(obj -> {
            TbScSgnlIxrSttsDto dto = obj.toSttsDto();
            if (total) {
                FcltSttsDto stts = FcltSttsDto.builder()
                        .fcltType(fcltType)
                        .fcltNmbr(String.valueOf(obj.getSgnlIxrNmbr()))
                        .fcltId(String.valueOf(obj.getSgnlIxrNmbr()))
                        .fcltNm(obj.getIxrNm())
                        .fcltKind("1")
                        .xCrdn(obj.getXPos())
                        .yCrdn(obj.getYPos())
                        .strmUrl("")
                        .sttsCd(dto.getCmncSttsCd())
                        .sttsDesc(dto.getCmncSttsDesc())
                        .build();

                sttsDtoList.add(stts);
            }
            if (CodeManager.CMNC_STTS_NORMAL.equals(dto.getCmncSttsCd())) {
                normal.getAndIncrement();
            }
            else {
                error.getAndIncrement();
            }
        });

        FcltSttsSummaryDto summaryDto = FcltSttsSummaryDto.builder()
                .fcltType(fcltType)
                .fcltNm(fcltType)
                .totalCnt(ctlrList.size())
                .normalCnt(normal.get())
                .errorCnt(error.get())
                .colErrCnt(0)
                .build();

        summaryDto.init();
        if (total) {
            summaryDto.setFcltObjs(sttsDtoList);
        }
        result.getFcltList().add(summaryDto);

        return result;
    }

}
