
import HTMLContainer from "../HTMLContainer";
import Locator from "../../services/Locator";
import {createDeferredPromise} from "../../utils/createDeferredPromise";


function div(className) {
  const view = document.createElement("div");
  view.className = className;
  return view;
}
function button(name, callback, className = "") {
  const view = document.createElement("button");
  view.className = className;
  view.addEventListener("pointerdown", callback);
  view.innerHTML = name;
  return view;
}

class PopupHtmlContainer extends HTMLContainer {

  constructor(parent, className = undefined) {
    super(parent, className);
    this.element.style.display = "flex";
    Locator.viewport.on("resize", this.updateTransform, this);
  }

  updateTransform() {
    // this.element.style.transformOrigin = `${this.anchor.x * 100}% ${this.anchor.y * 100}%`;

    const scale = Math.max(0.6, Locator.viewport.cropWidthRatio);
    let transform = `scale(${this.scale.x * scale}, ${this.scale.y * scale}`;
    this.element.style.transform = transform;
  }

  destroy() {
    super.destroy();
    Locator.viewport.off("resize", this.updateTransform, this);
  }
}


export function showErrorPopup({ header, msg, buttons}) {
  const deferred = createDeferredPromise();
  const view = div("error-popup");
  const body = new PopupHtmlContainer(view, "error-popup__body");
  body.element.innerHTML = `<div class='error-popup__header'><img class="error-popup__icon" src="${Locator.network.baseImgsUrl}/error_popup_icon.png"> ${header ? header : ""}</div><div class='error-popup__content'>${msg}</div>`;
  const buttonsRow = div("error-popup__buttons");
  body.element.append(buttonsRow);
  const okBtn = button("Ok", () => {
    body.element.style.scale = 0;
    view.style.opacity = 0;
    setTimeout(deferred.resolve, 200);
  });

  buttonsRow.append(okBtn);

  if (buttons) {
    for (const btn of buttons) {
      if (btn.url) {
        const btnDom = button(btn.name, () => {
          window.location.assign(btn.url);
        });
        buttonsRow.append(btnDom);
      }
    }
  }


  body.element.append(buttonsRow);
  document.body.append(view);

  view.addEventListener("pointerdown", (e) => e.preventDefault());
  view.addEventListener("pointerup", (e) => e.preventDefault());

  body.anchor.set(0.5);
  const resize = () => {
    const htmlFactor = Locator.viewport.heightRatio;
    body.scale.set(htmlFactor);
  };

  resize();

  Locator.viewport.on("resize", resize);

  setTimeout(() => {
    body.element.style.scale = 1;
    view.style.opacity = 1;
  }, 5);

  deferred.promise.then(() => {
    body.destroy();
    view.remove();
  });
  return deferred.promise;
}
