package com.its.op.scheduler.job;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.its.op.dto.its.unit.TbUnitSystSttsDto;
import com.its.op.service.its.unit.TbUnitSystService;
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 UnitSttsJobThread {

    private final Environment environment;
    private final TbUnitSystService unitSystService;
    private ObjectMapper mapper;

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

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

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

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

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

        // ITS Unit Stts
        List<TbUnitSystSttsDto> itsUnitStts = this.unitSystService.findAllStts();
        ItsWebSocketMessage itsMessage = new ItsWebSocketMessage("itsUnitStts", itsUnitStts);
        try {
            String itsSttsJsonData = this.mapper.writeValueAsString(itsMessage);
            ItsWebSocketSessionManager.getInstance().sendBroadcastMessage(itsMessage.getCommand(), new TextMessage(itsSttsJsonData));
        }
        catch(JsonProcessingException e){
            log.error("UnitSttsJobThread ItsFcltSttsDto Json parsing Exception: {}", itsUnitStts);
        }

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