import streamDeck, { SingletonAction } from "@elgato/streamdeck";
import { wsManager } from "../websocket-manager.js";
import { generateResetButton } from "../image-generator.js";

/**
 * Reset Session Action
 *
 * Clears all play history, allowing the session to start fresh.
 */
export class ResetAction extends SingletonAction {
  manifestId = "com.djliveplaylist.reset";

  // Store action references for updating button images
  actions = new Map();

  constructor() {
    super();

    // Update button when connection state changes
    wsManager.on("connected", () => this.updateAllButtons());
    wsManager.on("disconnected", () => this.updateAllButtons());
  }

  onWillAppear(ev) {
    const actionId = ev.action.id;
    this.actions.set(actionId, { action: ev.action });
    this.updateButton(actionId);
  }

  onWillDisappear(ev) {
    this.actions.delete(ev.action.id);
  }

  async onKeyDown(ev) {
    if (!wsManager.isConnected) {
      streamDeck.logger.warn("Cannot reset: not connected to DLP");
      return;
    }

    wsManager.send("RESET_SESSION", {});
    streamDeck.logger.info("Reset session requested");
  }

  async updateButton(actionId) {
    const entry = this.actions.get(actionId);
    if (!entry) return;

    const image = generateResetButton({ isConnected: wsManager.isConnected });
    entry.action.setImage(image);
  }

  updateAllButtons() {
    for (const actionId of this.actions.keys()) {
      this.updateButton(actionId);
    }
  }
}
