package com.its.op.scheduler.job;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.its.op.dto.its.common.FcltSttsListDto;
import com.its.op.service.its.common.CommonSttsService;
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;

@Slf4j
@RequiredArgsConstructor
@Service
public class FcltSttsJobThread {

    private final Environment environment;
    private final CommonSttsService itsService;
    private ObjectMapper mapper;

    @PostConstruct
    private void init() {
        this.mapper = new ObjectMapper();

        log.info("{}", this);
    }

    @Async("schJobExecutor")
    public void run() {

        log.info("START: FcltSttsJobThread.run: {}", Thread.currentThread().getName());

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

        // ITS Fclt Stts
        FcltSttsListDto itsSttsDto = this.itsService.findAllFcltSttsTotal();
        ItsWebSocketMessage itsMessage = new ItsWebSocketMessage("itsFcltStts", itsSttsDto);
        try {
            String itsSttsJsonData = this.mapper.writeValueAsString(itsMessage);
            ItsWebSocketSessionManager.getInstance().sendBroadcastMessage(itsMessage.getCommand(), new TextMessage(itsSttsJsonData));
        }
        catch(JsonProcessingException e){
            log.error("FcltSttsJobThread ItsFcltSttsDto Json parsing Exception: {}", itsSttsDto);
        }

        stopWatch.stop();
        log.info("--END: FcltSttsJobThread.run: {}, {} ms.", Thread.currentThread().getName(), stopWatch.getTotalTimeMillis());
    }
}
