import { readFileSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { getServerStatus, stopServer } from './ssh.js';
import { getPlayers } from './rcon.js';
import { getAllAutoShutdownSettings, getAutoShutdownSettings } from '../db/init.js';

const __dirname = dirname(fileURLToPath(import.meta.url));

// Track when each server became empty
const emptyPlayersSince = new Map();

// Check interval in ms (60 seconds)
const CHECK_INTERVAL = 60000;

function loadConfig() {
  return JSON.parse(readFileSync(join(__dirname, '..', 'config.json'), 'utf-8'));
}

async function checkServers() {
  try {
    const config = loadConfig();
    const enabledSettings = getAllAutoShutdownSettings();
    
    // Create a map for quick lookup
    const settingsMap = new Map(enabledSettings.map(s => [s.server_id, s]));
    
    for (const server of config.servers) {
      const settings = settingsMap.get(server.id);
      
      // Skip if auto-shutdown not enabled for this server
      if (!settings || !settings.enabled) {
        emptyPlayersSince.delete(server.id);
        continue;
      }
      
      try {
        // Check if server is online
        const status = await getServerStatus(server);
        
        if (status !== 'online') {
          // Server not running, clear timer
          emptyPlayersSince.delete(server.id);
          continue;
        }
        
        // Get player count
        let playerCount = 0;
        if (server.rconPassword) {
          const players = await getPlayers(server);
          playerCount = players.online || 0;
        }
        
        if (playerCount === 0) {
          // No players online
          if (!emptyPlayersSince.has(server.id)) {
            // Start tracking empty time
            emptyPlayersSince.set(server.id, Date.now());
            console.log(`[AutoShutdown] ${server.id}: Keine Spieler online, Timer gestartet`);
          }
          
          const emptyMs = Date.now() - emptyPlayersSince.get(server.id);
          const emptyMinutes = emptyMs / 60000;
          
          if (emptyMinutes >= settings.timeout_minutes) {
            console.log(`[AutoShutdown] ${server.id}: Timeout erreicht (${settings.timeout_minutes} Min), stoppe Server...`);
            await stopServer(server);
            emptyPlayersSince.delete(server.id);
            console.log(`[AutoShutdown] ${server.id}: Server gestoppt`);
          }
        } else {
          // Players online, reset timer
          if (emptyPlayersSince.has(server.id)) {
            console.log(`[AutoShutdown] ${server.id}: Spieler online (${playerCount}), Timer zurückgesetzt`);
            emptyPlayersSince.delete(server.id);
          }
        }
      } catch (err) {
        console.error(`[AutoShutdown] Fehler bei ${server.id}:`, err.message);
      }
    }
  } catch (err) {
    console.error('[AutoShutdown] Fehler beim Laden der Config:', err.message);
  }
}

export function startAutoShutdownService() {
  console.log('[AutoShutdown] Service gestartet, prüfe alle 60 Sekunden');
  
  // Initial check after 10 seconds (give server time to start)
  setTimeout(() => {
    checkServers();
  }, 10000);
  
  // Then check every 60 seconds
  setInterval(checkServers, CHECK_INTERVAL);
}

// Get how long a server has been empty (for status display)
export function getEmptySince(serverId) {
  const since = emptyPlayersSince.get(serverId);
  if (!since) return null;
  return Math.floor((Date.now() - since) / 60000); // Return minutes
}

// Get all empty-since times
export function getAllEmptySince() {
  const result = {};
  for (const [serverId, since] of emptyPlayersSince) {
    result[serverId] = Math.floor((Date.now() - since) / 60000);
  }
  return result;
}
