package com.tsi.sig.server.websocket;


import com.tsi.sig.server.config.KafkaConsumerConfig;
import com.tsi.sig.server.websocket.kafka.OneTopicConsumerThread;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;

import java.util.ArrayList;
import java.util.List;

@Slf4j
//@Controller
//@RequestMapping("/oneTopic.do")
public class OneTopicCvimHandler {
//        extends TextWebSocketHandler {

    private final KafkaConsumerConfig kafkaConsumerConfig;
    private List<WebSocketSession> webSocketSessions = new ArrayList<WebSocketSession>();
    private OneTopicConsumerThread consumerThread = null;
    private Thread thread;

    public OneTopicCvimHandler(KafkaConsumerConfig kafkaConsumerConfig) {
        this.kafkaConsumerConfig = kafkaConsumerConfig;
        this.consumerThread = new OneTopicConsumerThread(this, this.kafkaConsumerConfig);
    }

//    @Override
//    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
//        // 클라이언트가 연결되었을때 실행
//        this.webSocketSessions.add(session);
//        log.info("OneTopicCvimHandler, WebSocket [in]  RemoteAddress: " + session.getRemoteAddress() + ",  Uri" + session.getUri() + ", UUID" + session.getId());
//    }

    //클라이언트가 웹소켓 서버로 메시지를 전송했을 때 실행
//    @Override
//    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
//        try {
//            this.consumerThread.addNodeSession(session, message.getPayload());
//            log.info("OneTopicCvimHandler, [recv] SessionIP : "+ session.getRemoteAddress() + ", NodeID : "+ message.getPayload() + ", Session :+" + session.toString());
//        } catch (Exception e) {
////            e.printStackTrace();
//            log.error("OneTopicCvimHandler Add Session Failed");
//        }
//    }

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

//    @Override
//    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
//        log.error(exception.toString());
//    }

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

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

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

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