/**
 * WebSocket connection
 * Uses MockWebSocket in MOCK_MODE, otherwise real WebSocket
 */

var RobotWebSocket = (function() {
    var socket = null;
    var listeners = [];
    var statusListeners = [];
    var reconnectInterval = null;
    var isConnected = false;

    function connect() {
        var WebSocketClass = Config.getWebSocketClass();
        var url = Config.WS_URL;

        console.log('[WebSocket] Connecting to', url, '(Mock:', Config.MOCK_MODE, ')');

        try {
            socket = new WebSocketClass(url);

            socket.onopen = function() {
                console.log('[WebSocket] Connected');
                isConnected = true;
                clearReconnect();
                notifyStatusListeners(true);
            };

            socket.onmessage = function(event) {
                try {
                    var state = JSON.parse(event.data);
                    notifyListeners(state);
                } catch (e) {
                    console.error('[WebSocket] Parse error:', e);
                }
            };

            socket.onclose = function() {
                console.log('[WebSocket] Disconnected');
                isConnected = false;
                notifyStatusListeners(false);
                scheduleReconnect();
            };

            socket.onerror = function(error) {
                console.error('[WebSocket] Error:', error);
            };

        } catch (e) {
            console.error('[WebSocket] Connection failed:', e);
            scheduleReconnect();
        }
    }

    function disconnect() {
        clearReconnect();
        if (socket) {
            socket.close();
            socket = null;
        }
        isConnected = false;
    }

    function scheduleReconnect() {
        if (reconnectInterval) return;
        if (Config.MOCK_MODE) return;

        reconnectInterval = setInterval(function() {
            if (!isConnected) {
                console.log('[WebSocket] Reconnecting...');
                connect();
            }
        }, 3000);
    }

    function clearReconnect() {
        if (reconnectInterval) {
            clearInterval(reconnectInterval);
            reconnectInterval = null;
        }
    }

    function notifyListeners(state) {
        listeners.forEach(function(cb) {
            cb(state);
        });
    }

    function notifyStatusListeners(connected) {
        statusListeners.forEach(function(cb) {
            cb(connected);
        });
    }

    return {
        connect: connect,
        disconnect: disconnect,

        isConnected: function() {
            return isConnected;
        },

        onMessage: function(callback) {
            listeners.push(callback);
        },

        onStatusChange: function(callback) {
            statusListeners.push(callback);
        }
    };
})();
