/**
 * autoRefresh.js - Auto-refresh functionality
 * 
 * This module handles the automatic refreshing of dashboard data.
 */

import AppState from './state.js';
import { loadReportData } from './api.js';
import { fetchUserStates } from './api.js';
import { showLogMessage } from './uiHelpers.js';

/**
 * Toggle auto-refresh on/off
 */
export function toggleAutoRefresh() {
    const autoRefreshBtn = document.getElementById('autoRefreshBtn');
    const autoRefreshIndicator = document.getElementById('autoRefreshIndicator');
    
    if (!AppState || typeof AppState.isAutoRefreshEnabled !== 'function' || typeof AppState.setAutoRefreshEnabled !== 'function' || typeof AppState.getAutoRefreshInterval !== 'function') {
        console.error("AppState or its methods are not available in toggleAutoRefresh.");
        return;
    }
    if (!autoRefreshBtn || !autoRefreshIndicator) {
        console.error("UI elements for auto-refresh not found in toggleAutoRefresh.");
        return;
    }

    const currentState = AppState.isAutoRefreshEnabled();
    AppState.setAutoRefreshEnabled(!currentState);
    
    if (AppState.isAutoRefreshEnabled()) {
        // Enable auto-refresh
        startAutoRefresh();
        autoRefreshBtn.innerHTML = '<i class="bi bi-pause-circle"></i> Pause Auto-refresh';
        autoRefreshIndicator.classList.remove('d-none');
        showLogMessage('Auto-refresh enabled. Dashboard will update every ' + 
            (AppState.getAutoRefreshInterval()/1000) + ' seconds.');
    } else {
        // Disable auto-refresh
        stopAutoRefresh();
        autoRefreshBtn.innerHTML = '<i class="bi bi-play-circle"></i> Resume Auto-refresh';
        autoRefreshIndicator.classList.add('d-none');
        showLogMessage('Auto-refresh paused. Manual refresh required.');
    }
}

/**
 * Start auto-refresh timer
 */
export function startAutoRefresh() {
    if (!AppState || typeof AppState.getAutoRefreshTimer !== 'function' || typeof AppState.setAutoRefreshTimer !== 'function' || typeof AppState.getAutoRefreshInterval !== 'function' || typeof AppState.setLastRefreshTime !== 'function') {
        console.error("AppState or its methods are not available in startAutoRefresh.");
        return;
    }

    if (AppState.getAutoRefreshTimer()) {
        clearInterval(AppState.getAutoRefreshTimer());
    }
    
    // Start a new timer
    const timer = setInterval(performAutoRefresh, AppState.getAutoRefreshInterval());
    AppState.setAutoRefreshTimer(timer);
    AppState.setLastRefreshTime(Date.now());
    updateRefreshIndicator();
    
    // Start updating the indicator
    startRefreshCountdown();
}

/**
 * Stop auto-refresh timer
 */
export function stopAutoRefresh() {
    if (!AppState || typeof AppState.getAutoRefreshTimer !== 'function' || typeof AppState.setAutoRefreshTimer !== 'function') {
        console.error("AppState or its methods are not available in stopAutoRefresh.");
        return;
    }

    if (AppState.getAutoRefreshTimer()) {
        clearInterval(AppState.getAutoRefreshTimer());
        AppState.setAutoRefreshTimer(null);
    }
    
    // Stop updating the indicator
    stopRefreshCountdown();
}

/**
 * Perform the actual refresh
 */
export async function performAutoRefresh() {
    console.log('Auto-refreshing dashboard...');
    if (AppState && typeof AppState.setLastRefreshTime === 'function') {
        AppState.setLastRefreshTime(Date.now());
    } else {
        console.error("AppState.setLastRefreshTime is not available in performAutoRefresh.");
    }
    
    try {
        // First update user states
        await fetchUserStates(true);
        
        // Then reload report data
        await loadReportData(true); // Pass true to indicate it's an auto-refresh
        
        showLogMessage('Dashboard auto-refreshed successfully');
    } catch (error) {
        console.error('Auto-refresh error:', error);
        showLogMessage('Auto-refresh error: ' + error.message);
    }
}

/**
 * Update refresh indicator display
 */
export function updateRefreshIndicator() {
    const autoRefreshIndicator = document.getElementById('autoRefreshIndicator');
    
    if (!AppState || typeof AppState.isAutoRefreshEnabled !== 'function' || typeof AppState.getLastRefreshTime !== 'function' || typeof AppState.getAutoRefreshInterval !== 'function') {
        console.error("AppState or its methods are not available in updateRefreshIndicator.");
        return;
    }
    if (!autoRefreshIndicator) {
        // If indicator is not present, just return silently. It might not be on all pages/views.
        return;
    }
    
    if (!AppState.isAutoRefreshEnabled()) return;
    
    const elapsedSeconds = Math.floor((Date.now() - AppState.getLastRefreshTime()) / 1000);
    const remainingSeconds = Math.max(0, Math.floor(AppState.getAutoRefreshInterval() / 1000) - elapsedSeconds);
    
    autoRefreshIndicator.textContent = 'Auto-refresh in ' + remainingSeconds + 's';
}

/**
 * Start refresh countdown timer
 */
export function startRefreshCountdown() {
    if (!AppState || typeof AppState.getCountdownTimer !== 'function' || typeof AppState.setCountdownTimer !== 'function') {
        console.error("AppState or its methods are not available in startRefreshCountdown.");
        return;
    }

    if (AppState.getCountdownTimer()) {
        clearInterval(AppState.getCountdownTimer());
    }
    
    // Update immediately, then start the interval
    updateRefreshIndicator();
    const timer = setInterval(updateRefreshIndicator, 1000);
    AppState.setCountdownTimer(timer);
}

/**
 * Stop refresh countdown timer
 */
export function stopRefreshCountdown() {
    if (!AppState || typeof AppState.getCountdownTimer !== 'function' || typeof AppState.setCountdownTimer !== 'function') {
        console.error("AppState or its methods are not available in stopRefreshCountdown.");
        return;
    }

    if (AppState.getCountdownTimer()) {
        clearInterval(AppState.getCountdownTimer());
        AppState.setCountdownTimer(null);
    }
}

/**
 * Initialize auto-refresh functionality
 */
export function initializeAutoRefresh() {
    const autoRefreshBtn = document.getElementById('autoRefreshBtn');
    const autoRefreshIndicator = document.getElementById('autoRefreshIndicator');

    if (!AppState || typeof AppState.isAutoRefreshEnabled !== 'function' || typeof AppState.getAutoRefreshInterval !== 'function') {
        console.error("AppState or its methods are not available for initializing auto-refresh.");
        // Attempt to gracefully handle if AppState is not ready, maybe auto-refresh remains off.
        if (autoRefreshBtn) autoRefreshBtn.innerHTML = '<i class="bi bi-play-circle"></i> Resume Auto-refresh';
        if (autoRefreshIndicator) autoRefreshIndicator.classList.add('d-none');
        return;
    }
    
    // Set up event listener for the auto-refresh button
    if (autoRefreshBtn) {
        autoRefreshBtn.addEventListener('click', toggleAutoRefresh);
        // Synchronize button text/icon with initial state
        if (AppState.isAutoRefreshEnabled()) {
            autoRefreshBtn.innerHTML = '<i class="bi bi-pause-circle"></i> Pause Auto-refresh';
        } else {
            autoRefreshBtn.innerHTML = '<i class="bi bi-play-circle"></i> Resume Auto-refresh';
        }
    }
    
    // Initialize auto-refresh indicator
    if (autoRefreshIndicator) {
        if (AppState.isAutoRefreshEnabled()) {
            autoRefreshIndicator.classList.remove('d-none');
        } else {
            autoRefreshIndicator.classList.add('d-none');
        }
    }
    
    // Start auto-refresh if enabled
    if (AppState.isAutoRefreshEnabled()) {
        startAutoRefresh();
    }
} 