/*eslint no-undef:0*/
/*eslint-env browser*/

"use strict";
var app = app || {};

app.runapirequest = (destmodalid, axiosreq, modalcontent) => {
  /**
   * Axios option
   * {method: GET POST,...,
   * url:'/relativepath'
   * data:{anydata to pass}
   * responseType:'json'}
   */
  if (!modalcontent) {
    modalcontent = {
      title: "An axios request",
      body: "",
      actions: [],
    };
  }
  modalcontent.body += JSON.stringify(axiosreq);
  console.log(apx.data.headers);
  axiosreq.headers = apx.data.headers;
  axios(axiosreq)
    .then((rep) => {
      console.log(rep);
      modalcontent.body += "<br>" + JSON.stringify(rep.data);
      app.modalmanagement("reqaxios", apx.data.tpl.apxmodal, modalcontent);
    })
    .catch((err, rep) => {
      console.log(err);
      modalcontent.title += " - Status :" + err.response.status;
      modalcontent.body += JSON.stringify(err.response.data);
      app.modalmanagement("reqaxios", apx.data.tpl.apxmodal, modalcontent);
    });
};
app.modalmanagement = (modalid, tpl, data, optionmodal) => {
  /**
   * Pre-request in hatml
   * <div id="apxmodal" add2data tpl="static/tpl/apxmodal_en.mustache" ></div>
   * data must be online with tpl
   *  optionmodal see https://getbootstrap.com/docs/5.0/components/modal/
   */
  if (!optionmodal)
    optionmodal = { backdrop: true, keyboard: true, focus: true };
  if (document.getElementById(modalid)) {
    document.getElementById(modalid).remove();
  }
  data.modalid = modalid;
  document.getElementById("apxmodal").innerHTML += Mustache.render(tpl, data);
  var currentmodal = new bootstrap.Modal(
    document.getElementById(modalid),
    optionmodal
  );
  //var currentmodal = bootstrap.Modal.getOrCreateInstance(modalid);

  currentmodal.show();
};
app.search = (elt) => {
  //@todo get search string from input then return tpldata.articleslist={"search":[]}
  console.log("A FAIRE");
};
app.downloadlink = (keys, object, prefix) => {
  /**
   *
   * @param {string} split(.) to naviagte in object until a subobject
   * @param {object} a json object
   *
   * Create a link that download subobject as a textfile
   * example:
   *  const obj={pagans:{privateKey:"123", publicKey:"AZE"}}
   *  const prefix = "appname"
   *  const keys="pagans.privateKey"
   *
   * in <html>
   *  <button class="btn btn-outline-primary" onclick="app.downloadlink('pagans.privateKey',obj,prefix);" >Download PrivateKey</button>
   *
   *
   */
  const dwn = (fn, t) => {
    var element = document.createElement("a");
    element.setAttribute(
      "href",
      "data:text/plain;charset=utf-8," + encodeURIComponent(t)
    );
    element.setAttribute("download", fn);
    element.style.display = "none";
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
  };
  const subobj = keys.split(".").reduce((val, k) => (val = val[k]), object);
  const txt = typeof subobj == "string" ? subobj : JSON.stringify(subobj);
  dwn(`${prefix}_${keys.split(".").pop()}.txt`, txt);
};

app.setupdata = () => {
  //todo generate tpldata.articleslist get html from /static/html
  apx.data.tpldata.articleslist = {
    mostread: [{}],
    news: [{}],
    search: [],
    articles: "html",
  };
  const list = {};
  document.querySelectorAll("[add2data]").forEach((e) => {
    /**  Collect from any tag with add2data url attribute (tpl tpldata object)
     *    name is the filename :
     *    for tpl and tpldata (relativepath/filename_xx.ext) name=filename
     *    For public object (pagans, towns, nations, block) not tribes object are gettable (only)
     *      with /nationchains/objectName/idx/existingindex.json
     *      or for an item               /itm//primarykey_value_of_item.json
     *
     *    For tribe object get or for modification you need to use api and to have accessright setup properly:
     *    for object index (/api/odmdb/objectname/idx/filename.json) name =objectname_filename
     *    for object item  (/api/odmdb/objectname/itm/primarykey.json) name =objectname_primarykey
     */

    if (e.getAttribute("object")) {
      const url = e.getAttribute("object");
      const spliturlobj = url.split("/").slice(-3);
      const objectname = spliturlobj[0];
      const objecttype = spliturlobj[1];
      const objectkey = spliturlobj[2].substring(0, spliturlobj[2].length - 5);
      if (!list[objectname]) list[objectname] = {};
      list[objectname][`${objecttype}${objectkey}`] = url;
    }
    for (let k of ["tpl", "tpldata"]) {
      if (e.getAttribute(k)) {
        const url = e.getAttribute(k);
        let localname = url.split("/").slice(-1)[0];
        if (url.includes(".mustache"))
          localname = localname.substring(0, localname.length - 12);
        if (url.includes(".html") || url.includes(".json"))
          localname = localname.substring(0, localname.length - 8);
        if (!list[k]) list[k] = {};
        list[k][localname] = url;
      }
    }
  });
  // load external template and data

  for (let k of Object.keys(list)) {
    console.log(k, list[k]);
    apx.loadfile(list[k], k);
  }
  //alert(apx.data.firsttimeload)
  if (apx.data.firsttimeload) {
    // Need to wait the first time apx.data fully load
    setTimeout(() => {
      app.setuppage();
    }, 500);
    delete apx.data.firsttimeload;
    apx.save();
  } else {
    app.setuppage();
  }
};
app.load = (idtoload, tplname, tpldata) => {
  const tpl = apx.data.tpl[tplname]
    ? apx.data.tpl[tplname]
    : `missing template ${tplname}`;
  const data = typeof tpldata == "string" ? apx.data.tpldata[tpldata] : tpldata;
  document.getElementById(idtoload).innerHTML = Mustache.render(tpl, data);
};
app.setuppage = () => {
  // load partial template
  document.querySelectorAll("[apptoload]").forEach((e) => {
    console.log(e.getAttribute("apptoload"));
    eval(e.getAttribute("apptoload"));
  });
};
apx.ready(app.setupdata);
