package com.tsi.sig.server.websocket;

import com.tsi.sig.server.config.KafkaEvpConsumerConfig;
import com.tsi.sig.server.websocket.kafka.EvpTopicConsumerThread;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.net.ConnectException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
//@Controller
//@RequestMapping("/evpTopic.do")
@Component
public class EvpTopicHandler {
//        extends TextWebSocketHandler {

    private final KafkaEvpConsumerConfig kafkaEvpConsumerConfig;

    private List<WebSocketSession> sessionList = new ArrayList<WebSocketSession>();
    private EvpTopicConsumerThread consumerThread = null;
    private Thread thread;

    public EvpTopicHandler(KafkaEvpConsumerConfig kafkaEvpConsumerConfig) {
        this.kafkaEvpConsumerConfig = kafkaEvpConsumerConfig;
        this.consumerThread = new EvpTopicConsumerThread(this, this.kafkaEvpConsumerConfig);
    }
//    @Override
//    public void afterConnectionEstablished(WebSocketSession session) throws Exception, IOException {
        // 클라이언트가 연결되었을때 실행
//        try {
//            this.sessionList.add(session);
//            this.consumerThread.addSession(session);
//        } catch (Exception e) {
//            log.error("EvpTopicCvimHandler Add Session Failed");
//        }
//        log.info("EvpTopicCvimHandler, WebSocket [in]  RemoteAddress: " + session.getRemoteAddress() + ",  Uri" + session.getUri() + ", UUID" + session.getId());
//    }

    //클라이언트가 웹소켓 서버로 메시지를 전송했을 때 실행
//    @Override
//    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception, IOException {
//    }

    //클라이언트 연결을 끊었을 때 실행
//    @Override
//    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception, IOException {
//        try {
//            this.consumerThread.removeSession(session);
//            this.sessionList.remove(session);
//        } catch (Exception e) {
//            log.error("EvpTopicCvimHandler Remove Session Failed");
//        }
//        log.info("EvpTopicCvimHandler, WebSocket [out]  RemoteAddress: " + session.getRemoteAddress() + ",  Uri: " + session.getUri() + ", UUID: " + session.getId());
//    }

//    public void sendMessage(WebSocketSession session, TextMessage message) {
//
//        if (session != null && session.isOpen()) {
//            synchronized (session) {
//                try {
//                    session.sendMessage(message);
//                } catch (Exception e) {
//                    log.error("EvpTopicCvimHandler, sendMessage: session: {}, {}", session, e.getMessage());
//                    log.error("EvpTopicCvimHandler, sendMessage: session: {}", session);
//                }
//            }
//        }
//    }

    public void shutdown() {
        if (!this.consumerThread.getStopFlag().get()) {
            this.consumerThread.shutdown();
        }
    }

    public void start() throws Exception, ConnectException {
        if (this.consumerThread.getStopFlag().get()) {
            log.info("EvpTopicCvimHandler, Start by stopFlag. {}", this.consumerThread);
            this.thread = null;
            this.consumerThread = null;
            this.consumerThread = new EvpTopicConsumerThread(this, this.kafkaEvpConsumerConfig);
            this.thread = new Thread(this.consumerThread);
            this.thread.setUncaughtExceptionHandler(
                    (th, ex) -> {
                        log.error("Uncaught exception : EvpTopicCvimHandler");
                        shutdown();
                    }
            );
            this.thread.start();
        }
    }

    public void stop() {
//        try {
            if (!this.consumerThread.getStopFlag().get()) {
                this.consumerThread.stop();
            }
//        }
//        catch (Exception e) {
//            log.error("EvpTopicCvimHandler Thread Stop Failed");
//        }
    }
}
