package com.its.vms.service;

import com.its.vms.config.ApplicationConfig;
import com.its.vms.dao.mapper.VmsAtmpMapper;
import com.its.vms.dto.TbVmsAtmpDto;
import com.its.vms.entity.TbVmsAtmp;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
@RequiredArgsConstructor
public class VmsAtmpService {

    private final ApplicationConfig config;
    private final VmsAtmpMapper vmsAtmpMapper;

    public ConcurrentHashMap<Long, TbVmsAtmp> atmpMap = new ConcurrentHashMap<>();

    public void loadAtmpInfo() {
        loadVmsAtmpInfo();
    }

    public void loadVmsAtmpInfo() {
        AtomicInteger nFailed = new AtomicInteger();
        AtomicInteger nSuccess = new AtomicInteger();
        try {
            List<TbVmsAtmpDto> infoList  = this.vmsAtmpMapper.selectVmsAtmpInfo();
            log.info("VmsAtmpService.loadVmsAtmpInfo(), {} EA", infoList.size());
            infoList.forEach(dto -> {
                TbVmsAtmp obj = dto.toEntity();
                this.atmpMap.put(obj.getAtmpSttnNmbr(), obj);
                if (obj.getMsrmDt() == null) {
                    obj.setSuccess(false);
                    nFailed.getAndIncrement();
                    return;
                }
                if ("0".equals(obj.getPm101hhGrad()) &&
                    "0".equals(obj.getPm251hhGrad()) &&
                    "0".equals(obj.getIntgAtmpGrad())) {
                    obj.setSuccess(false);
                    nFailed.getAndIncrement();
                    return;
                }
                log.error("{}", obj);
                nSuccess.getAndIncrement();
            });
        }
        catch (Exception e) {
            log.error("VmsAtmpService.loadVmsAtmpInfo: {}", e.toString());
        }

        if (nFailed.intValue() > 0 && nSuccess.intValue() > 0) {
            // 성공 데이터가 존재하고 실패 데이터가 존재하는 경우 데이터 보정
            correctVmsAtmpInfo();
        }
    }

    public void correctVmsAtmpInfo() {
        /**
         * 측정 데이터가 없는 경우 정상적인 측정 데이터를 가지고 보정한다.
         */
        TbVmsAtmp vmsAtmp = null;
        for (Map.Entry<Long, TbVmsAtmp > obj : this.atmpMap.entrySet()) {
            if (obj.getValue().isSuccess()) {
                vmsAtmp = obj.getValue();
                break;
            }
        }
        if (vmsAtmp == null) {
            return;
        }
        for (Map.Entry<Long, TbVmsAtmp > obj : this.atmpMap.entrySet()) {
            if (!obj.getValue().isSuccess()) {
                vmsAtmp.correct(obj.getValue());
            }
        }
    }
}
