package com.dspread.pos.common.websocket;

import android.util.Log;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class WebSocketManager {
    private WebSocketClient webSocketClient;
    private WebSocketListener listener;
    private ScheduledExecutorService executorService;
    private String serverUrl;
    private boolean shouldReconnect = true;
    private static final int RECONNECT_DELAY_SECONDS = 5;

    public interface WebSocketListener {
        void onMessageReceived(String message);
        void onConnectionEstablished();
        void onConnectionClosed();
        void onError(String error);
    }

    public WebSocketManager(WebSocketListener listener) {
        this.listener = listener;
        this.executorService = Executors.newSingleThreadScheduledExecutor();
    }

    public void connect(String serverUrl) {
        this.serverUrl = serverUrl;
        internalConnect();
    }

    private void internalConnect() {
        try {
            URI uri = new URI(serverUrl);

            webSocketClient = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    listener.onConnectionEstablished();
                    // Reset reconnect flag on successful connection
                    shouldReconnect = true;
                }

                @Override
                public void onMessage(String message) {
                    listener.onMessageReceived(message);
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    listener.onConnectionClosed();
                    scheduleReconnect();
                }

                @Override
                public void onError(Exception ex) {
                    listener.onError(ex.getMessage());
                    scheduleReconnect();
                }
            };

            webSocketClient.connect();
        } catch (Exception e) {
            listener.onError(e.getMessage());
            scheduleReconnect();
        }
    }

    private void scheduleReconnect() {
        if (shouldReconnect) {
            executorService.schedule(() -> {
                if (!isConnected()) {
                    internalConnect();
                }
            }, RECONNECT_DELAY_SECONDS, TimeUnit.SECONDS);
        }
    }

    public void sendMessage(String message) {
        if (webSocketClient != null && webSocketClient.isOpen()) {
            webSocketClient.send(message);
        }
    }

    public void disconnect() {
        shouldReconnect = false;
        if (webSocketClient != null) {
            webSocketClient.close();
        }
        executorService.shutdown();
    }

    public boolean isConnected() {
        return webSocketClient != null && webSocketClient.isOpen();
    }
}