package com.its.api.scheduler.job;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.its.api.bis.service.BitService;
import com.its.api.its.model.dto.common.FcltSttsListDto;
import com.its.api.its.service.common.CommonSttsService;
import com.its.api.websocket.ItsWebSocketMessage;
import com.its.api.websocket.ItsWebSocketSessionManager;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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
@AllArgsConstructor
@Service
public class FcltSttsJobThread {

    private final CommonSttsService itsService;
    private final BitService bitService;
    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, e.getMessage());
        }

        // BIS BIT Stts
        FcltSttsListDto bitSttsDto = this.bitService.findAllListSttsTotal();
        ItsWebSocketMessage bisMessage = new ItsWebSocketMessage("bisFcltStts", bitSttsDto);
        try {
            String bitSttsJsonData = this.mapper.writeValueAsString(bisMessage);
            ItsWebSocketSessionManager.getInstance().sendBroadcastMessage(bisMessage.getCommand(), new TextMessage(bitSttsJsonData));
        }
        catch(JsonProcessingException e){
            log.error("FcltSttsJobThread BisFcltSttsDto Json parsing Exception: {}, {}", itsSttsDto, e.getMessage());
        }

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