package com.tsi.sig.server.repository;

import com.tsi.sig.server.dto.EvpsData;
import com.tsi.sig.server.vo.CvibNodeStatusVo;
import com.tsi.sig.server.vo.CvibNodeVO;
import com.tsi.sig.server.vo.CvibStatusVo;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Getter
@Service
public class ApplicationRepository {
    private final List<CvibNodeVO> nodeList = new ArrayList<>();
    private final Map<String, CvibNodeStatusVo> nodeStatusMap = new HashMap<>();
    private final Map<String, EvpsData> evpDataMap = new HashMap<>();
    public List<CvibStatusVo> getStatusList() throws ParseException {
        List<CvibStatusVo> list = new ArrayList<>();

        if (this.nodeStatusMap.size() > 0) {
            List<CvibNodeStatusVo> originList = new ArrayList<>(this.nodeStatusMap.values());
            for (CvibNodeStatusVo vo : originList) {
                CvibStatusVo newVo = new CvibStatusVo();
                newVo.setNodeId(vo.nodeId);
                newVo.setCommStatus(vo.commStatus);
                newVo.setLocalDate(vo.localDate);
                newVo.setConnDate(vo.connDate);
                list.add(newVo);
                Date connDate = null;
                Date date = null;
                Date now = new Date();
                if (vo.getConnDate() != null) {
                    connDate = this.getStringParseToDate(vo.getConnDate());
                }

                if (vo.getLocalDate() != null) {
                    date = this.getStringParseToDate(vo.getLocalDate());
                }
                if ( date != null &&
                     connDate != null &&
                     connDate.getTime() - date.getTime() > 10000) {
                     //log.warn("=========== OverTime 3 Seconds.....  nodeId : {}, OverTime : {} ms",
                     //       vo.nodeId,connDate.getTime() - date.getTime());
                    //newVo.setCommStatus(false);
                }
                else if (date != null && connDate != null && now.getTime() - connDate.getTime() > 10000) {
                    newVo.setCommStatus(false);
                }
                else if(!vo.commStatus) {
                   // log.warn("=========== 통신 이상...  nodeId : {}",vo.nodeId);
                }

            }
        }
        return list;
    }

    public Date getStringParseToDate(String date) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.parse(date);
    }
}
