import type { StatusUpdateEvent, PingGWEvent } from './types';

// Main splash screen functionality
class SplashScreen {
  private statusElement: HTMLElement;
  private versionElement: HTMLElement;
  private copyrightElement: HTMLElement;

  constructor() {
    this.statusElement = document.getElementById('status')!;
    this.versionElement = document.getElementById('version')!;
    this.copyrightElement = document.getElementById('copyright')!;
    
    this.init();
  }

  private init(): void {
    this.setupGlue42Listeners();
    this.setupUI();
  }

  private setupGlue42Listeners(): void {
    // Listen for status updates from the main process
    if (window.glue42splash) {
      window.glue42splash.on("updateStatus", (arg: StatusUpdateEvent) => {
        this.updateStatus(arg.text);
      });

      window.glue42splash.on("pingGW", (arg: PingGWEvent) => {
        this.testGatewayConnection(arg.gwURL);
      });
    }
  }

  private setupUI(): void {
    // Update copyright with current year
    const year = new Date().getFullYear();
    this.copyrightElement.innerHTML = `&copy; ${year} ${this.copyrightElement.innerHTML}`;

    // Parse URL parameters for initial setup
    this.parseUrlParams();
  }

  private parseUrlParams(): void {
    // Parse url params - splash.html?message=Starting&env=DEMO&region=INTEROP.IO&version=9.0.0.25
    const urlParams = new URLSearchParams(window.location.search);
    
    const message = urlParams.get("message");
    if (message) {
      this.updateStatus(message);
    }

    const version = urlParams.get("version");
    if (version) {
      const env = urlParams.get("env");
      const region = urlParams.get("region");
      this.versionElement.innerHTML = `${version} (${env}) - ${region}`;
    }
  }

  private updateStatus(message: string): void {
    console.log(`updating status to ${message}`);
    this.statusElement.innerHTML = message + "...";
  }

  private testGatewayConnection(gwURL: string): void {
    const retry = () => {
      console.log(`testing connectivity to ${gwURL}`);

      const webSocket = new WebSocket(gwURL);
      console.log(webSocket);

      webSocket.onopen = () => {
        console.log(`received open from GW on ${gwURL} - resolving...`);
        webSocket.close();
      };

      webSocket.onerror = (err) => {
        console.log(`received error from GW on ${gwURL} - will retry`, err);
        setTimeout(() => {
          retry();
        }, 500);
      };
    };

    retry();
  }
}

// Initialize the splash screen when the DOM is loaded
document.addEventListener("DOMContentLoaded", () => {
  new SplashScreen();
});
