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

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

towns.loadtpldata = (fortpl) => {
  // adapte tpldata to template tpl
  if (fortpl == "owner") {
    const dataowner = apx.data.tpldata.setup;
    dataowner.alias = apx.data.headers.xalias;
    dataowner.auth = dataowner.alias != "anonymous";
    dataowner.devtown = dataowner.townId == "devfarm";
    if (dataowner.mayorId)
      dataowner.owner = dataowner.mayorId == dataowner.alias;
    console.log("Data return to template", dataowner);
    return dataowner;
  }
  if (fortpl == "tribes") {
    const data= {
      idcomponent: "tribesmanager",
      objectname:"tribes",
      itm: [
        { tribeId: "tribe1", druidId: "philc" },
        { tribeId: "tribe2", druidId: "toto" },
      ]
    };
    data.tplform=` 
      <div class='mb-3'>
        <label for='tribeIdinput' class='form-label'>Tribes Name</label>
        <input type='text' class='form-control' id='tribIdinput' placeholder='A unique name'>
      </div>
      <div class='mb-3'>
        <label for='druidIdinput' class='form-label'>Druid Alias</label>
        <input type='text' class='form-control' id='druidIdinput' placeholder='An existing alias to become Tribe's Druid'>
      </div>
      <div class='input-group mb-3 objaction'>
          <button class=' objsave btn btn-outline-primary btn-sm' onclick='towns.addupdatetribe('{{tribeId');'><i class='bi-cloud-arrow-up'></i></button> 
      </div>`;
    return data;
  }
};
towns.owntown = (newowner) => {
  // only the owner can give ownership to someone else
  if (!newowner) {
    newowner = apx.data.headers.xalias;
  }
  axios
    .get(`api/towns/changeowner/${newowner}`, { headers: apx.data.headers })
    .then((rep) => {
      console.log(rep);
      apx.data.tpldata.setup.mayorId = newowner;
      apx.save();
      app.load("apxmain", "townowner", towns.loadtpldata("owner"));
    })
    .catch((err) => {
      console.log(err);
    });
};
towns.addtribe=(tribeId)=>{

}