import "jquery"
import "JSON";
import "../vendor/jquery.lazy";
import "../vendor/jquery-ui";
// import "blueimp-file-upload";
import "imports-loader?define=>false!blueimp-file-upload";

import "./webforms9neu/jquery-autocomplete";
import "./webforms9neu/jquery-format";
import "./webforms9neu/jquery-webforms";
import "../modules/webforms"


// Loging for the webforms in case of error
document.addEventListener("mwf-ajax-finished", (eventData) => {
  if (eventData.detail && eventData.detail.$dest) {
    const errorDiv = $(eventData.detail.$dest).find("p:contains(There has been an error while processing the form)");
    if (errorDiv.length) {
      const dataSettings = $('[data-mwf-settings]').data();
      let errorText = "";
      if(dataSettings && dataSettings.mwfSettings) {
        errorText = "Frontend Form Url:" + dataSettings.mwfSettings.url
      }
      errorText = errorText + errorDiv.parent().parent().html();

      $.ajax({
        url: "/blueprint/servlet/webformslogging/log",
        type: "POST",
        contentType: "text/html",
        traditional: true,
        cache: false,
        data: errorText
      }).done(function (stringData) {
        console.log("loging response", stringData);
      }).fail(function (jqXHR) {
        console.log("Error logging failed", jqXHR.responseText);
      });
    }
    const dataSuccess = $(eventData.detail.$dest).data("succes-template");
    if(dataSuccess){
      $("#webformsDetailText").hide();
      $(".anchorlinks").hide();
      $(".text.initial").hide();
    }
  }
});

/**
 * JS for rendering webforms as webcomponent.
 * Mandatory Attributes added to the <webforms-component>:
 * - formId: webform id
 * - navigationId: parent navigation chanel
 *
 * Optional Attributes added to the <webforms-component>:
 * - sendSubmittedEvent (true / false|default): emits custom event("gfi-webforms-submited") after special action "Aufgabe" is submited
 * - loadCSS (true|default / false): should the component load own css
 * - optionalDomainUrl (String.Empty|default): in some cases component is unable to calculate its domain url.
 * Either set the domain url or id on the including script
 *
 * Optional Attribute added to te including script.
 * - webformsComponentScript (id): in some cases component is unable to calculate its domain url.
 * Either set the domain url or id on the including script.
 */

class WebformsComponent extends HTMLElement {
  constructor() {
    super();
  }

  connectedCallback() {
    const optionalDomainUrl = this.getAttribute("optionalDomainUrl");
    const optionalScriptId = document.getElementById("webformsComponentScript");
    this.mandantUrl = "";

    if (optionalDomainUrl) {
      this.mandantUrl = optionalDomainUrl;
    } else if (optionalScriptId) {
      const scriptUrl = optionalScriptId.src;
      this.mandantUrl = new URL(scriptUrl).origin;
    } else {
      const scriptUrl = document.currentScript.src;
      this.mandantUrl = new URL(scriptUrl).origin;
    }


    this.prefillServerUrl = this.getAttribute("prefillServerUrl");
    if (this.prefillServerUrl) {
      this.prefillWebform();
    } else {
      this.writeWebformsHtml();
    }

    this.shouldTriggerSubmittedEvent = this.getAttribute("sendSubmittedEvent");
    if (this.shouldTriggerSubmittedEvent) {
      document.addEventListener("mwf-ajax-finished", (eventData) => {
        const aufgabeData = $(eventData.detail.$dest).data("aufgabedata");
        if (aufgabeData) {
          document.dispatchEvent(new CustomEvent("gfi-webforms-submitted", {detail: aufgabeData}))
        }
      });
    }
  }

  prefillWebform() {
    const t = this;
    const principleId = $.getUrlVar(window.location.search, "principle");
    const processId = $.getUrlVar(window.location.search, "processId");
    const contentId = this.getAttribute("formId");
    const prefillUrl = this.mandantUrl + "/blueprint/servlet/serviceport/aufgabe/prefill/" + principleId + "/" + processId + "/" + contentId;


    $.ajax({
      url: prefillUrl,
      type: "GET",
      traditional: true,
      cache: false,
      xhrFields: {withCredentials: true}
    }).done(function (stringData) {
      const queryString = $.param(t.parseDataToJson(stringData));
      t.writeWebformsHtml(queryString);
    }).fail(function (jqXHR) {
      console.log("Prefill request failed", jqXHR.responseText);
      t.writeWebformsHtml();
    })
  }

  parseDataToJson(stringData) {
    try {
      // TODO: schöner schreiben, dient nur für POC
      const anmerkungenObj = {};
      const parsedData = JSON.parse(stringData).variablen.filter((elem) => elem.name === "anmerkungen")[0];
      anmerkungenObj[parsedData.name] = parsedData.wert;
      return anmerkungenObj;
    } catch (e) {
      console.log("Aufgabedata parsen ist fehlgeschlagen", e);
      return {}
    }
  }

  writeWebformsHtml(prefillData) {
    const formId = this.getAttribute("formId");
    const navigationId = this.getAttribute("navigationId");
    const shouldLoadCss = this.getAttribute("loadCSS");

    if (shouldLoadCss !== "false") {
      $("head").append("<link rel='stylesheet'  href='" + this.mandantUrl + "/blueprint/default/responsive/css/webforms-component.css' type='text/css' />");
    }

    if (prefillData) {
      this.innerHTML = `<div data-mwf-form='${formId}' data-mwf-settings='{
              "url":"${this.mandantUrl}/blueprint/servlet/mwf-form/${formId}?view=ajax&${prefillData}",
                      "query":"navigationId=${navigationId}",
                      "appendUrlVars":"true"
                      }'></div>`;

    } else {
      this.innerHTML = `<div data-mwf-form='${formId}' data-mwf-settings='{
              "url":"${this.mandantUrl}/blueprint/servlet/mwf-form/${formId}?view=ajax",
                      "query":"navigationId=${navigationId}",
                      "appendUrlVars":"true"}'></div>`;

    }
    // webforms need to be initialised in case they have not noticed new elements.
    // Sometimes we get 2 same requests but it is ok
    $('[data-mwf-form]').webforms({});

  }


}

window.customElements.define('webforms-component', WebformsComponent);
