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>
      </div>
    `;

    return el;
  }

  ready() {
    super.ready();

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

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

  renderMessage(payload) {
    const message =
      getErrorDisplayMessage(this.player(), (key, tokens) =>
        tokens ? this.localize(key, tokens) : this.localize(key)
      ) ||
      (payload?.messageKey
        ? payload.messageTokens
          ? this.localize(payload.messageKey, payload.messageTokens)
          : this.localize(payload.messageKey)
        : null) ||
      payload?.message?.trim() ||
      this.localize("errorUnknown");
    this.messageEl_.textContent = message;
  }

  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;
