// Real-time Status Checker - Monitor online/offline status of IP addresses
class StatusChecker {
    constructor(configUrl = 'config.php') {
        this.configUrl = configUrl;
        this.checkInterval = null;
        this.isActive = true;
        this.statusCallbacks = new Map(); // IP -> callback function
        this.currentStatuses = new Map(); // IP -> status object
    }

    // Check status of a specific IP address
    async checkStatus(ip) {
        try {
            const response = await fetch(`${this.configUrl}?checkstatus=true&ip=${encodeURIComponent(ip)}`, {
                method: 'GET',
                headers: {
                    'Cache-Control': 'no-cache',
                    'Pragma': 'no-cache'
                }
            });

            if (response.ok) {
                const data = await response.json();
                console.log(`Status check for ${ip}:`, data.status, `(${data.timeDiff}s ago)`);

                // Store current status
                this.currentStatuses.set(ip, data);

                // Call callback if registered
                const callback = this.statusCallbacks.get(ip);
                if (callback && typeof callback === 'function') {
                    callback(data);
                }

                return data;
            } else {
                console.error('Status check failed:', response.status);
                return null;
            }
        } catch (error) {
            console.error('Status check error:', error);
            return null;
        }
    }

    // Start monitoring a specific IP with callback
    startMonitoring(ip, callback, interval = 3000) {
        // Register callback for this IP
        if (callback && typeof callback === 'function') {
            this.statusCallbacks.set(ip, callback);
        }

        // Perform initial check
        this.checkStatus(ip);

        // Set up interval for continuous monitoring
        const monitorInterval = setInterval(() => {
            if (this.isActive) {
                this.checkStatus(ip);
            }
        }, interval);

        console.log(`Started monitoring IP ${ip} every ${interval}ms`);
        return monitorInterval;
    }

    // Stop monitoring a specific IP
    stopMonitoring(ip, interval) {
        if (interval) {
            clearInterval(interval);
        }
        this.statusCallbacks.delete(ip);
        this.currentStatuses.delete(ip);
        console.log(`Stopped monitoring IP ${ip}`);
    }

    // Get current status of an IP (from cache)
    getCurrentStatus(ip) {
        return this.currentStatuses.get(ip) || null;
    }

    // Check if IP is online (from cache)
    isOnline(ip) {
        const status = this.getCurrentStatus(ip);
        return status ? status.status === 'online' : false;
    }

    // Get all monitored IPs and their statuses
    getAllStatuses() {
        const statuses = {};
        this.currentStatuses.forEach((status, ip) => {
            statuses[ip] = status;
        });
        return statuses;
    }

    // Simple status display helper
    displayStatus(ip, elementId) {
        const callback = (data) => {
            const element = document.getElementById(elementId);
            if (element) {
                const statusClass = data.status === 'online' ? 'status-online' : 'status-offline';
                const timeDiffText = data.timeDiff !== null ? `(${data.timeDiff}s ago)` : '';

                element.innerHTML = `
                    <span class="${statusClass}">
                        ${data.ip}: ${data.status} ${timeDiffText}
                    </span>
                `;
                element.className = statusClass;
            }
        };

        return this.startMonitoring(ip, callback);
    }

    // Pause all monitoring
    pause() {
        this.isActive = false;
        console.log('Status monitoring paused');
    }

    // Resume all monitoring
    resume() {
        this.isActive = true;
        console.log('Status monitoring resumed');
    }

    // Stop all monitoring
    destroy() {
        this.pause();
        this.statusCallbacks.clear();
        this.currentStatuses.clear();
    }
}

// Helper function for simple usage
function createStatusMonitor(ip, callbackOrElementId, interval = 3000) {
    const monitor = new StatusChecker();

    if (typeof callbackOrElementId === 'string') {
        // If string provided, assume it's an element ID for display
        return monitor.displayStatus(ip, callbackOrElementId);
    } else if (typeof callbackOrElementId === 'function') {
        // If function provided, use it as callback
        return monitor.startMonitoring(ip, callbackOrElementId, interval);
    }
}

// Auto-initialize when script loads
document.addEventListener('DOMContentLoaded', function () {
    // Make StatusChecker available globally
    window.StatusChecker = StatusChecker;
    window.createStatusMonitor = createStatusMonitor;

    // Example CSS for status display (add to your stylesheet)
    if (!document.querySelector('#status-checker-styles')) {
        const style = document.createElement('style');
        style.id = 'status-checker-styles';
        style.textContent = `
            .status-online {
                color: #4CAF50;
                font-weight: bold;
            }
            .status-offline {
                color: #f44336;
                font-weight: bold;
            }
            .status-unknown {
                color: #9E9E9E;
                font-style: italic;
            }
        `;
        document.head.appendChild(style);
    }
});

// Export for module use if needed
if (typeof module !== 'undefined' && module.exports) {
    module.exports = StatusChecker;
}