import videojs from "video.js";
import {
  getErrorDisplayMessage,
  normalizePlayerError,
} from "../helpers/errorMessages.js";
import "../styles/error-overlay.css";

const Component = videojs.getComponent("Component");

class ErrorOverlay extends Component {
  constructor(player, options) {
    super(player, options);
    this.currentPayload = null;
  }

  createEl() {
    const el = super.createEl("div", {
      className: "videojs-drm-error-overlay",
    });
    el.style.display = "none";

    el.innerHTML = `
      <div class="videojs-drm-error-overlay__panel">
        <p class="videojs-drm-error-overlay__message"></p>
        <button type="button" class="videojs-drm-error-overlay__dismiss"></button>
      </div>
    `;

    return el;
  }

  ready() {
    super.ready();

    this.messageEl_ = this.el().querySelector(
      ".videojs-drm-error-overlay__message"
    );
    this.dismissButton_ = this.el().querySelector(
      ".videojs-drm-error-overlay__dismiss"
    );

    this.dismissButton_.addEventListener("click", () => this.hide());

    this.player().on("error", () => {
      const payload = normalizePlayerError(this.player().error());
      this.show(payload);
    });
  }

  renderMessage(payload) {
    const message =
      getErrorDisplayMessage(this.player(), (key) => this.localize(key)) ||
      payload?.message?.trim() ||
      this.localize("errorUnknown");
    this.messageEl_.textContent = message;
    this.dismissButton_.textContent = this.localize("Close");
  }

  show(payload = {}) {
    this.currentPayload = payload;
    this.renderMessage(payload);
    this.el().style.display = "flex";
    this.player().addClass("vjs-has-error-overlay");
  }

  hide() {
    this.currentPayload = null;
    this.el().style.display = "none";
    this.player().removeClass("vjs-has-error-overlay");

    if (typeof this.player().error === "function") {
      this.player().error(null);
    }
  }
}

videojs.registerComponent("ErrorOverlay", ErrorOverlay);

export default ErrorOverlay;
