import { BrowserSocketFactory, Client } from "./blitz.js";

export class DataStream extends EventTarget {
  constructor() {
    super();
    this.socketFactory = null;
    this.client = null;
    this.lastReceived = null;
    this.connectionTimeout = null;
    this.test = false;
    this.testInterval = null;
  }

  async init() {
    this.socketFactory = new BrowserSocketFactory();
    this.client = new Client(this.socketFactory);
    this.lastReceived = Date.now();

    this.setupWebSocketListeners();
    this.client.connect();
    this.resetTimeout();
  }

  resetTimeout() {
    clearTimeout(this.connectionTimeout);
    this.connectionTimeout = setTimeout(() => {
      console.log("No data received in 14 seconds, reconnecting...");
      this.reconnectWebSocket();
    }, 14999);
  }

  reconnectWebSocket() {
    if (this.client) {
      this.client.close();
    }
    this.client = new Client(new BrowserSocketFactory());
    this.setupWebSocketListeners();
    this.client.connect();
    this.resetTimeout();
  }

  setupWebSocketListeners() {
    if (this.test === false) {
      this.client.removeAllListeners?.("data");
      this.client.removeAllListeners?.("error");
      this.client.removeAllListeners?.("close");

      this.client.on("data", (data) => {
        this.lastReceived = Date.now();
        this.resetTimeout();

        this.dispatchEvent(new CustomEvent("strike", { detail: data }));
      });

      this.client.on("error", (err) => {
        console.error("WebSocket error:", err);
        this.reconnectWebSocket();
      });

      this.client.on("close", () => {
        console.log("WebSocket closed, attempting to reconnect...");
        this.reconnectWebSocket();
      });
    } else {
      clearInterval(this.testInterval);
      this.testInterval = setInterval(() => {
        this.dispatchEvent(new CustomEvent("strike", { detail: "fakeData" }));
      }, 1000);
    }
  }
}
