// retoor <retoor@molodetz.nl>

import { UserScope } from "./userScope.js";

const SESSION_NAME = "devplace";

function persistKey() {
  return `ct-persistent:${UserScope.get()}`;
}

export class ContainerTerminalManager {
  constructor() {
    this._terminals = new Map();
    this._persistent = null;
  }

  open(projectSlug, instance, label) {
    if (!projectSlug || !instance) return null;
    const key = `${projectSlug}::${instance}`;
    const existing = this._terminals.get(key);
    if (existing && existing.isConnected) {
      this._makePersistent(existing, projectSlug, instance, label);
      if (globalThis.app && globalThis.app.windows) globalThis.app.windows.focus(existing);
      return existing;
    }
    this._demoteCurrent(null);
    const element = document.createElement("container-terminal");
    element.setAttribute("project-slug", projectSlug);
    element.setAttribute("instance", instance);
    if (label) element.setAttribute("label", label);
    element.setAttribute("session", SESSION_NAME);
    element.setAttribute("persist", "");
    document.body.appendChild(element);
    this._terminals.set(key, element);
    this._persistent = element;
    this._remember(projectSlug, instance, label);
    return element;
  }

  _makePersistent(element, projectSlug, instance, label) {
    this._demoteCurrent(element);
    element.setAttribute("session", SESSION_NAME);
    if (typeof element.setPersistent === "function") element.setPersistent(true);
    this._persistent = element;
    this._remember(projectSlug, instance, label);
  }

  _demoteCurrent(except) {
    if (this._persistent && this._persistent !== except && this._persistent.isConnected) {
      if (typeof this._persistent.setPersistent === "function") this._persistent.setPersistent(false);
    }
  }

  forget(element) {
    this._terminals.forEach((el, key) => {
      if (el === element) this._terminals.delete(key);
    });
    if (element === this._persistent) {
      this._persistent = null;
      this._clearRemember();
    }
  }

  restore() {
    let record = null;
    try {
      record = JSON.parse(window.localStorage.getItem(persistKey()) || "null");
    } catch (error) {
      record = null;
    }
    if (record && record.slug && record.instance) {
      this.open(record.slug, record.instance, record.label || record.instance);
    }
  }

  applyFontSize(size) {
    this._terminals.forEach((element) => {
      if (element.isConnected && typeof element.setFontSize === "function") {
        element.setFontSize(size);
        if (typeof element._syncControls === "function") element._syncControls();
      }
    });
  }

  _remember(slug, instance, label) {
    try {
      window.localStorage.setItem(persistKey(), JSON.stringify({ slug, instance, label: label || instance }));
    } catch (error) {
      return;
    }
  }

  _clearRemember() {
    try {
      window.localStorage.removeItem(persistKey());
    } catch (error) {
      return;
    }
  }
}
