/**
 * Real-time Statistics Service
 * برای دریافت آمار لحظه‌ای سرورها و کاربران
 */

export interface ServerStats {
  serverId: string;
  serverName: string;
  ping: number;
  load: number;
  bandwidth: {
    download: number;
    upload: number;
  };
  activeConnections: number;
  status: 'online' | 'offline' | 'maintenance';
}

export interface UsageStats {
  date: string;
  activeUsers: number;
  totalTraffic: number;
  newSubscriptions: number;
}

export class RealtimeStatsService {
  private ws: WebSocket | null = null;
  private reconnectAttempts = 0;
  private maxReconnectAttempts = 5;
  private reconnectDelay = 3000;

  constructor(private url: string = 'ws://localhost:8080/stats') {}

  connect(onMessage: (data: any) => void, onError?: (error: Event) => void) {
    try {
      this.ws = new WebSocket(this.url);

      this.ws.onopen = () => {
        console.log('WebSocket connected');
        this.reconnectAttempts = 0;
      };

      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          onMessage(data);
        } catch (error) {
          console.error('Failed to parse WebSocket message:', error);
        }
      };

      this.ws.onerror = (error) => {
        console.error('WebSocket error:', error);
        if (onError) onError(error);
      };

      this.ws.onclose = () => {
        console.log('WebSocket closed');
        this.attemptReconnect(onMessage, onError);
      };
    } catch (error) {
      console.error('Failed to create WebSocket:', error);
    }
  }

  private attemptReconnect(onMessage: (data: any) => void, onError?: (error: Event) => void) {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      console.log(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
      
      setTimeout(() => {
        this.connect(onMessage, onError);
      }, this.reconnectDelay);
    } else {
      console.error('Max reconnection attempts reached');
    }
  }

  disconnect() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
  }

  send(data: any) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(data));
    } else {
      console.warn('WebSocket is not connected');
    }
  }
}

// Mock data generator برای تست
export const generateMockServerStats = (): ServerStats[] => {
  const servers = ['ایران 1', 'آلمان 1', 'هلند 1', 'فرانسه 1', 'آمریکا 1'];
  
  return servers.map((name, index) => ({
    serverId: `server-${index + 1}`,
    serverName: name,
    ping: Math.floor(Math.random() * 200) + 50,
    load: Math.floor(Math.random() * 100),
    bandwidth: {
      download: Math.floor(Math.random() * 1000),
      upload: Math.floor(Math.random() * 500)
    },
    activeConnections: Math.floor(Math.random() * 100),
    status: Math.random() > 0.1 ? 'online' : 'offline'
  }));
};

export const generateMockUsageStats = (days: number = 30): UsageStats[] => {
  const stats: UsageStats[] = [];
  const today = new Date();

  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(date.getDate() - i);
    
    stats.push({
      date: date.toISOString().split('T')[0],
      activeUsers: Math.floor(Math.random() * 200) + 100,
      totalTraffic: Math.floor(Math.random() * 10000) + 5000,
      newSubscriptions: Math.floor(Math.random() * 20) + 5
    });
  }

  return stats;
};

// Singleton instance
let statsService: RealtimeStatsService | null = null;

export const getStatsService = () => {
  if (!statsService) {
    statsService = new RealtimeStatsService();
  }
  return statsService;
};
