import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class LiveReloadService {
  private socket: WebSocket | null = null;

  public initialize(): void {
    this.connect();
  }

  public connect(): void {
    if (this.socket) {
      return;
    }

    // Connect to the WebSocket server
    this.socket = new WebSocket('ws://localhost:42099');

    this.socket.onopen = () => {
      console.log('[LiveReloadClient] Connected to server');
    };

    this.socket.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data as string) as { type: string };
        if (data.type === 'reload') {
          console.log('[LiveReloadClient] Reload triggered');
          window.location.reload();
        }
      } catch (error) {
        console.error('[LiveReloadClient] Error processing message:', error);
      }
    };

    this.socket.onerror = (error) => {
      console.error('[LiveReloadClient] WebSocket error:', error);
    };

    this.socket.onclose = () => {
      console.log('[LiveReloadClient] Connection closed');
      this.socket = null;
      // Attempt to reconnect after a delay
      setTimeout(() => this.connect(), 5000);
    };
  }

  public disconnect(): void {
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  }
}
