import { html } from "lit-html";
import { styleMap } from "lit-html/directives/style-map.js";

import { dataUrlToBlob } from "./util";
import { ProfilePictureGeneratorSettings } from "./main";

function fileUpload(text: string, className: string[]) {
  return html`
    <label class=${className.join(" ")} tabindex="0">
      <span>${text}</span>
      <input
        type="file"
        accept="image/*"
        style=${styleMap({ display: "none" })}
        @change=${function(this: HTMLInputElement) {
          this.dispatchEvent(
            new CustomEvent("upload-avatar", {
              bubbles: true,
              detail: this.files[0]
            })
          );
        }}
      />
    </label>
  `;
}

function languageSelector(
  languages: { id: string; name: string }[],
  className: string[],
  ariaLabel: string
) {
  return html`
    <select
      class=${className.join(" ")}
      aria-label=${ariaLabel}
      style=${styleMap({
        display: languages.length < 2 ? "none" : "block"
      })}
      @change=${function(this: HTMLSelectElement) {
        this.dispatchEvent(
          new CustomEvent("change-language", {
            bubbles: true,
            detail: this.value
          })
        );
      }}
    >
      ${languages.map(
        ({ id, name }) =>
          html`
            <option value=${id}>${name}</option>
          `
      )}
    </select>
  `;
}

function zoomIcon() {
  return html`
    <!-- BEGIN OF LICENSED PART -->
    <!--
      MIT License

      Copyright (c) 2020 Refactoring UI Inc.

      Permission is hereby granted, free of charge, to any person obtaining a copy
      of this software and associated documentation files (the "Software"), to deal
      in the Software without restriction, including without limitation the rights
      to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      copies of the Software, and to permit persons to whom the Software is
      furnished to do so, subject to the following conditions:

      The above copyright notice and this permission notice shall be included in all
      copies or substantial portions of the Software.

      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      SOFTWARE.
    -->
    <svg
      xmlns="http://www.w3.org/2000/svg"
      style="width: 24px; height: 24px;"
      fill="none"
      viewBox="0 0 24 24"
      stroke="currentColor"
    >
      <path
        stroke-linecap="round"
        stroke-linejoin="round"
        stroke-width="2"
        d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"
      />
    </svg>
    <!-- END OF LICENSED PART -->
  `;
}

function zoomSlider(
  title: string,
  className: string[],
  menuClassName: string[],
) {
  // min and max are default values (making it explicit here though);
  // actual zoom factor will be non-linear
  return html`
    <div class=${className.join(" ")} aria-haspopup="true">
      <label for="zoom-factor" title="${title}">
        ${zoomIcon()}  
      </label>
      <input
        type="range"
        name="zoom-factor"
        class=${menuClassName.join(" ")}
        min="0"
        max="100"
        orient="vertical"
        @change=${function (this: HTMLInputElement) {
          this.dispatchEvent(
            new CustomEvent("change-zoom-factor", {
              bubbles: true,
              detail: this.value,
            })
          );
        }}
      />
    </div>
  `;
}

function imageElement(src: string, altText: string, className: string[]) {
  return html`
    <div class=${className.join(" ")}>
      <img
        style=${styleMap({ width: "100%" })}
        src=${src}
        alt=${altText}
      />
    </div>
  `;
}

function downloadElement(
  text: string,
  fileName: string,
  href: string,
  className: string[]
) {
  return html`
    <a
      class=${className.join(" ")}
      download=${fileName}
      href=${href}
      @click=${function(this: HTMLElement) {
        if (navigator.msSaveBlob) {
          navigator.msSaveBlob(dataUrlToBlob(href), fileName);
        }

        this.dispatchEvent(new CustomEvent("download", { bubbles: true }));
      }}
      @tab=${function(this: HTMLElement) {
        this.dispatchEvent(new CustomEvent("download", { bubbles: true }));
      }}
      >${text}</a
    >
  `;
}

function loadingScreen() {
  return html`
    <div class="loading-screen">
      <div class="fff-profile-picture-generator-spinner">
        <div
          class="fff-profile-picture-generator-spinner1 fff-profile-picture-generator-spinner-child"
        ></div>
        <div
          class="fff-profile-picture-generator-spinner2 fff-profile-picture-generator-spinner-child"
        ></div>
        <div
          class="fff-profile-picture-generator-spinner3 fff-profile-picture-generator-spinner-child"
        ></div>
        <div
          class="fff-profile-picture-generator-spinner4 fff-profile-picture-generator-spinner-child"
        ></div>
        <div
          class="fff-profile-picture-generator-spinner5 fff-profile-picture-generator-spinner-child"
        ></div>
        <div
          class="fff-profile-picture-generator-spinner6 fff-profile-picture-generator-spinner-child"
        ></div>
        <div
          class="fff-profile-picture-generator-spinner7 fff-profile-picture-generator-spinner-child"
        ></div>
        <div
          class="fff-profile-picture-generator-spinner8 fff-profile-picture-generator-spinner-child"
        ></div>
        <div
          class="fff-profile-picture-generator-spinner9 fff-profile-picture-generator-spinner-child"
        ></div>
        <div
          class="fff-profile-picture-generator-spinner10 fff-profile-picture-generator-spinner-child"
        ></div>
        <div
          class="fff-profile-picture-generator-spinner11 fff-profile-picture-generator-spinner-child"
        ></div>
        <div
          class="fff-profile-picture-generator-spinner12 fff-profile-picture-generator-spinner-child"
        ></div>
      </div>
    </div>
  `;
}

function privacyNote(text: string) {
  return html`
    <div class="fff-profile-picture-generator--privacy-note">${text}</div>
  `;
}

function privacyLink(text: string, link: string) {
  return html`
    <a class="fff-profile-picture-generator--privacy-note" href=${link}
      >${text}</a
    >
  `;
}

export function template(
  settings: ProfilePictureGeneratorSettings,
  state: { loading: boolean; downloadUrl: string }
) {
  const languages: { id: string; name: string }[] = Object.entries(
    settings.languages
  )
    .map(([id, { name }]) => ({
      id,
      name
    }))
    .sort(({ name: a }, { name: b }) => a.localeCompare(b));

  return html`
    <div class=${settings.buttonGroupClass.join(" ")}>
      ${languageSelector(
        languages,
        settings.languageSelectorClass,
        settings.languageSelectorLabel
      )}
      ${fileUpload(settings.uploadButtonTitle, settings.uploadButtonClass)}
      ${settings.zoom && state.downloadUrl ? zoomSlider(
        settings.zoomLabel,
        settings.dropDownClass.concat(settings.dropDownButtonClass),
        settings.dropDownMenuClass
      ) : null}
    </div>
    ${state.loading
      ? loadingScreen()
      : imageElement(
          state.downloadUrl ? state.downloadUrl : settings.imagePreview,
          settings.imageAltText,
          settings.imageClass
        )}
    ${state.downloadUrl
      ? downloadElement(
          settings.downloadButtonTitle,
          settings.fileName,
          state.downloadUrl,
          settings.downloadButtonClass
        )
      : null}
    ${privacyNote(settings.privacyNote)}
    ${privacyLink(settings.privacyLinkText, settings.privacyLink)}
  `;
}
