/**
 * Filename: SmartCardReader.js
 * Author: AB Circle Limited
 * Contact: info@abcircle.com
 * Version: 1.0.0.0
 * Origin Date: 2025-04-03
 * 
 * Description: SmartCardReader.js is a JavaScript library for managing smart card readers via WebSocket.
 * This library connects to a WebSocket server (default: ws://127.0.0.1:55002) to manage smart card readers.
 * It supports connecting/disconnecting readers, sending APDU/control commands, and updating UI elements.
 * Designed for flexibility, it can be used standalone or with custom UI integrations.
 
 * Copyright (c) 2025 AB Circle Limited

 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * 1. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 2. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the Software or the use or other dealings in the Software.
 *
 * Usage Example:
 * ```javascript
 * const reader = new SmartCardReader();
 * const readers = await reader.getReaders();
 * await reader.connect(readers[0]);
 * const response = await reader.sendAPDUcommand('00A40400', readers[0]);
 * console.log(response);
 * ```
 *
 * @class SmartCardReader
 * @param {string} [apiBaseUrl='ws://127.0.0.1:55002'] - The WebSocket server URL (optional).
 */
class SmartCardReader {
    // Private class properties
    #defaultApiBaseUrl = 'ws://127.0.0.1:55002'; // Default WebSocket URL
    #pendingResponses = new Map(); // Tracks responses by messageId
    #connectionPromise; // Ensures WebSocket is ready before commands

    /**
     * Initializes the WebSocket connection.
     * @param {string} [apiBaseUrl] - WebSocket server URL (defaults to 'ws://127.0.0.1:55002').
     */
    constructor(apiBaseUrl = this.#defaultApiBaseUrl) {
        this.apiBaseUrl = apiBaseUrl;
        this.ws = new WebSocket(apiBaseUrl);
        this.#connectionPromise = this.#setupWebSocket();
    }

    /**
     * Sets up WebSocket event handlers for connection, messages, errors, and closure.
     * @returns {Promise<void>} Resolves when the WebSocket connection is established.
     * @private
     */
    #setupWebSocket() {
        return new Promise((resolve, reject) => {
            this.ws.onopen = () => {
                console.log('WebSocket connected');
                resolve();
            };
            this.ws.onmessage = (event) => {
                try{
                    const data = JSON.parse(event.data);
                    if (data.type === 'reader_update') {
                        this.#onReaderUpdate(data.readers);
                    } else if (data.type === 'response') {
                        this.#resolvePending(data.messageId, data.response);
                    } else if (data.type === 'error') {
                        this.#resolvePending(data.messageId, { error: data.error });
                    }
                } catch (error) {
                    console.error('Error processing Websocket message:', error);
                }
            };
            this.ws.onerror = (error) => console.error('WebSocket error:', error);
            this.ws.onclose = () => {
                console.log('WebSocket closed');
                this.cancelPendingRequests();
            };
        });
    }

    /**
     * Resolves a pending response based on messageId.
     * @param {number} messageId - Unique identifier for the request.
     * @param {Object} response - Response data or error object.
     * @private
     */
    #resolvePending(messageId, response) {
        const resolve = this.#pendingResponses.get(messageId);
        if (resolve) {
            resolve(response);
            this.#pendingResponses.delete(messageId);
        }
    }

    /**
     * Cancels all pending requests with an error message.
     * Useful when the WebSocket connection closes unexpectedly.
     */
    cancelPendingRequests() {
        this.#pendingResponses.forEach((resolve, messageId) => {
            resolve({ error: 'WebSocket connection closed or request cancelled' });
            this.#pendingResponses.delete(messageId);
        });
    }

    /**
     * Dispatches a custom event with reader updates for real-time monitoring.
     * @param {Array} readers - Array of reader details from the server.
     * @private
     */
    #onReaderUpdate(readers) {
        window.dispatchEvent(new CustomEvent('readerUpdate', { detail: readers }));
    }

    /**
     * Sends a command to the WebSocket server and awaits the response.
     * @param {string} endpoint - Server endpoint (e.g., '/reader_connect').
     * @param {Object} [payload={}] - Data to send with the command.
     * @returns {Promise<Object>} Response from the server.
     * @private
     */
    async #sendWebSocketCommand(endpoint, payload = {}) {
        await this.#connectionPromise;
        const messageId = Date.now();
        const message = { endpoint, payload, messageId };
        this.ws.send(JSON.stringify(message));
        return new Promise((resolve, reject) => {
            this.#pendingResponses.set(messageId, resolve);
            setTimeout(() => {
                if (this.#pendingResponses.has(messageId)) {
                    this.#pendingResponses.delete(messageId);
                    reject(new Error(`Timeout: No response for message ${messageId} after 10s`));
                }
            }, 10000);
        });
    }
    
    /**
     * Retrieves a list of available smart card readers.
     * @returns {Promise<string[]>} Array of reader names.
     * @throws {Error} If the WebSocket request fails.
     */
    async getReaders() {
        const response = await this.#sendWebSocketCommand('/reader_list');
        return response.readers || [];
    }

    /**
     * Retrieves detailed information about connected readers.
     * @returns {Promise<Object[]>} Array of objects with reader details (name, status, ATR).
     */
    async getReaderDetails() {
        const response = await this.#sendWebSocketCommand('/reader_info');
        return response.readers || [];
    }

    /**
     * Connects to a smart card reader.
     * @param {string} readerName - Name of the reader to connect to.
     * @param {string} [sharedMode='shared'] - Connection mode: 'shared' (multiple apps) or 'direct' (exclusive).
     * @param {string} [protocol='t1'] - Protocol: 't0' or 't1' (ignored in direct mode).
     * @returns {Promise<Object>} Response with hcard (handle) and ATR (if shared mode).
     * @throws {Error} If readerName is missing or connection fails.
     */
    async connect(readerName, sharedMode = 'shared', protocol = 't1') {
        if (!readerName) throw new Error('Reader name is required');
        const response = await this.#sendWebSocketCommand('/reader_connect', {
            command: readerName, sharedmode: sharedMode, protocol
        });
        return response;
    }

    /**
     * Disconnects from a smart card reader.
     * @param {string} readerName - Name of the reader to disconnect.
     * @param {string} [sharedMode='shared'] - Connection mode used during connect.
     * @returns {Promise<Object>} Disconnection response (e.g., "Success").
     * @throws {Error} If readerName is missing or disconnection fails.
     */
    async disconnect(readerName, sharedMode = 'shared') {
        if (!readerName) throw new Error('Reader name is required');
        const response = await this.#sendWebSocketCommand('/reader_disconnect', {
            command: readerName, sharedmode: sharedMode
        });
        return response;
    }

    /**
     * Sends an APDU command to a connected reader.
     * @param {string} command - Hexadecimal APDU command (e.g., '00A40400').
     * @param {string} readerName - Name of the target reader.
     * @returns {Promise<Object>} Response as a hex string (e.g., '9000').
     * @throws {Error} If readerName or command is missing.
     */
    async sendAPDUcommand(command, readerName) {
        if (!readerName || !command) throw new Error('Reader name and command are required');
        return await this.#sendWebSocketCommand('/reader_APDUcommand', { command, reader_name: readerName });
    }

    /**
     * Sends a control (Escape) command to a connected reader.
     * @param {string} command - Hexadecimal control command.
     * @param {string} readerName - Name of the target reader.
     * @returns {Promise<Object>} Response as a hex string.
     * @throws {Error} If readerName or command is missing.
     */
    async sendControlcommand(command, readerName) {
        if (!readerName || !command) throw new Error('Reader name and command are required');
        return await this.#sendWebSocketCommand('/reader_Controlcommand', { command, reader_name: readerName });
    }

    /**
     * Extracts the numeric suffix from a DOM element ID.
     * @param {string} id - DOM element ID (e.g., 'readerDropdown1').
     * @returns {string|null} Numeric suffix or null if not found.
     * @private
     */
    #getNumericSuffix(id) {
        const match = id.match(/\d+$/);
        if (!match) {
            console.error(`No numeric suffix found in ID: ${id}`);
            return null;
        }
        return match[0];
    }

    /**
     * Gets the selected reader name from a dropdown.
     * @param {string} readerDropdownId - ID of the reader dropdown element.
     * @returns {string|null} Selected reader name or null if none selected.
     * @private
     */
    #getSelectedReader(readerDropdownId) {
        const dropdown = document.getElementById(readerDropdownId);
        const selectedReader = dropdown?.value;
        if (!selectedReader) {
            alert('Please select a reader first!');
            return null;
        }
        return selectedReader;
    }

    // UI Helper Methods (below are optional for DOM integration)
    /**
     * Refreshes the list of readers in a dropdown element.
     * @param {string} readerDropdownId - ID of the dropdown element.
     * @returns {Promise<void>}
     */
    async refreshReader(readerDropdownId) {
        const dropdown = document.getElementById(readerDropdownId);
        if (!dropdown) {
            console.warn(`Dropdown with ID ${readerDropdownId} not found`);
            return;
        }
        try {
            const readers = await this.getReaders();
            dropdown.innerHTML = '<option value="" disabled selected>Select a reader</option>';
            if (readers.length === 0) {
                dropdown.innerHTML += '<option value="" disabled>No readers available</option>';
            } else {
                readers.forEach(reader => {
                    const option = new Option(reader, reader);
                    dropdown.appendChild(option);
                });
            }
        } catch (error) {
            console.error(`Failed to refresh dropdown ${readerDropdownId}:`, error);
        }
    }

    /**
     * Connects to a reader and updates the UI.
     * @param {string} readerDropdownId - ID of the dropdown element.
     * @param {string} [sharedMode='shared'] - Connection mode.
     * @param {string} [protocol='t1'] - Protocol.
     * @returns {Promise<void>}
     */
    async connectWithUI(readerDropdownId, sharedMode = 'shared', protocol = 't1') {
        const readerName = this.#getSelectedReader(readerDropdownId);
        if (!readerName) return;
        try {
            const response = await this.connect(readerName, sharedMode, protocol);
            this.#updateConnectionUI(response, readerName, readerDropdownId, sharedMode);
        } catch (error) {
            this.#handleError(readerDropdownId, error);
        }
    }

    /**
     * Disconnects from a reader and updates the UI.
     * @param {string} readerDropdownId - ID of the reader dropdown.
     * @param {string} [sharedMode='shared'] - Connection mode.
     * @returns {Promise<void>}
     */
    async disconnectWithUI(readerDropdownId, sharedMode = 'shared') {
        const readerName = this.#getSelectedReader(readerDropdownId);
        if (!readerName) return;
        try {
            await this.disconnect(readerName, sharedMode);
            this.#updateDisconnectionUI(readerDropdownId);
        } catch (error) {
            this.#handleError(readerDropdownId, error);
        }
    }

    /**
     * Sends an APDU command and updates the UI with the response.
     * @param {string} command - APDU command to send.
     * @param {string} readerDropdownId - ID of the reader dropdown.
     * @returns {Promise<void>}
     */
    async sendAPDUcommandWithUI(command, readerDropdownId) {
        const readerName = this.#getSelectedReader(readerDropdownId);
        if (!readerName) return;
        try {
            const response = await this.sendAPDUcommand(command, readerName);
            this.#updateResponseUI(readerDropdownId, response);
        } catch (error) {
            this.#handleError(readerDropdownId, error);
        }
    }

    /**
     * Sends a control command and updates the UI with the response.
     * @param {string} command - Control command to send.
     * @param {string} readerDropdownId - ID of the reader dropdown.
     * @returns {Promise<void>}
     */
    async sendControlcommandWithUI(command, readerDropdownId) {
        const readerName = this.#getSelectedReader(readerDropdownId);
        if (!readerName) return;
        try {
            const response = await this.sendControlcommand(command, readerName);
            this.#updateResponseUI(readerDropdownId, response);
        } catch (error) {
            this.#handleError(readerDropdownId, error);
        }
    }

    /**
     * Updates the UI after a successful connection.
     * @param {Object} data - Connection response from the server.
     * @param {string} readerName - Name of the connected reader.
     * @param {string} readerDropdownId - ID of the dropdown.
     * @param {string} sharedMode - Connection mode.
     * @private
     */
    #updateConnectionUI(data, readerName, readerDropdownId, sharedMode) {
        console.log('Connect response:', data);
        const suffix = this.#getNumericSuffix(readerDropdownId);
        if (!suffix) return;
        const responseDiv = document.getElementById(`response${suffix}`);
        const connectButton = document.getElementById(`connectButton${suffix}`);
        if (responseDiv) {
            if (data.error) {
                responseDiv.textContent = data.error;
            } else {
                responseDiv.textContent = sharedMode === 'shared'
                    ? (data.atr || 'No ATR data available')
                    : 'Connect Direct Mode.';
                if (connectButton && data.hcard) connectButton.textContent = 'Disconnect';
            }
        }
    }

    /**
     * Updates the UI after disconnection.
     * @param {string} readerDropdownId - ID of the dropdown.
     * @private
     */
    #updateDisconnectionUI(readerDropdownId) {
        const suffix = this.#getNumericSuffix(readerDropdownId);
        if (!suffix) return;
        const responseDiv = document.getElementById(`response${suffix}`);
        const connectButton = document.getElementById(`connectButton${suffix}`);
        if (responseDiv) responseDiv.textContent = 'Disconnected successfully.';
        if (connectButton) connectButton.textContent = 'Connect';
    }

    /**
     * Updates the UI with a command response.
     * @param {string} readerDropdownId - ID of the dropdown.
     * @param {Object} response - Command response from the server.
     * @private
     */
    #updateResponseUI(readerDropdownId, response) {
        const suffix = this.#getNumericSuffix(readerDropdownId);
        if (!suffix) return;
        const responseDiv = document.getElementById(`response${suffix}`);
        if (responseDiv) {
            if (response.error) {
                responseDiv.textContent = response.error;
            } else if (response.response) {
                responseDiv.textContent = response.response;
            } else {
                responseDiv.textContent = response || 'Command executed';
            }
        }
    }

    /**
     * Displays an error message in the UI.
     * @param {string} readerDropdownId - ID of the dropdown.
     * @param {Error} error - Error object.
     * @private
     */
    #handleError(readerDropdownId, error) {
        const suffix = this.#getNumericSuffix(readerDropdownId);
        if (!suffix) return;
        const responseDiv = document.getElementById(`response${suffix}`);
        if (responseDiv) responseDiv.textContent = error.message || 'An error occurred';
    }

}

export default SmartCardReader;