package com.its.op.scheduler.job;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.its.op.dto.its.scrs.TbScSgnlCtlrPhaseDto;
import com.its.op.service.its.scrs.TbScSgnlCtlrService;
import com.its.op.websocket.ItsWebSocketMessage;
import com.its.op.websocket.ItsWebSocketSessionManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;
import org.springframework.web.socket.TextMessage;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class SigPhaseJobThread {

    private final Environment environment;
    private final TbScSgnlCtlrService service;
    private ObjectMapper mapper;

    @PostConstruct
    private void init() {
        this.mapper = new ObjectMapper();
        log.info("{}", this);
    }

    @Async("schJobExecutor")
    public void run() {
        //log.info("START: SigPhaseJobThread.run: {}", Thread.currentThread().getName());

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        List<TbScSgnlCtlrPhaseDto> sigPhaseDto = this.service.findAllPhaseList();
        ItsWebSocketMessage itsMessage = new ItsWebSocketMessage("sigPhaseStts", sigPhaseDto);
        try {
            String itsSttsJsonData = this.mapper.writeValueAsString(itsMessage);
            ItsWebSocketSessionManager.getInstance().sendBroadcastSigPhaseMessage(itsMessage.getCommand(), new TextMessage(itsSttsJsonData));
        }
        catch(JsonProcessingException e){
            log.error("SigPhaseJobThread TbScSgnlCtlrPhaseDto Json parsing Exception: {}", sigPhaseDto);
        }

        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        if (totalTimeMillis > 2000) {
            log.warn("--END: SigPhaseJobThread.run: {}, {} ms.", Thread.currentThread().getName(), totalTimeMillis);
        }
    }
}
