/**
 * Description: Setting SoundFonts to synth.
 *
 * @package     midi-Synth
 * @category    module js
 * @author      Oleg Klenitsky <https://adminkov.bcr.by/midi/>
 * @copyright
 * @license     GPL-2.0-or-later
 */

var soundFont;

/**
 * [tblTimbreSF description]
 * @param  {[type]} activeZones     [description]
 * @return {[type]}                 [description]
 */
function tblTimbreSF(activeZones){
  if(false == Array.isArray(activeZones)) activeZones = activeZones.zones;

  let countRows = activeZones.length;
  let tblBody = document.querySelector("#soundViewerGSXG tbody");

  tblBody.innerHTML = "";

  // console.log("soundFont:", soundFont);
  // console.log("activeZones:", activeZones);

  for(let i=0; i<=countRows-1; i++){
    let row = document.createElement("tr");

    for(let j=0; j<=5; j++){
      let td  = document.createElement("td");
      let obj;
      switch(j){
        case 0: //Preset
          td.innerHTML = "zone: "+i;
          if(1 == countRows){
            td.setAttribute("style", "margin: 0 6px; padding:3px; height: 183px; text-align: center;");
          }else{
            td.setAttribute("style", "margin: 0 6px; padding:3px; height: 92px; text-align: center;");
          }
        break;
        case 1: //keyRange
          if(undefined !== activeZones[i].zones){
            td.innerHTML = "lo:"+activeZones[i].zones[0].keyRange.lo+", hi:"+activeZones[i].zones[0].keyRange.hi;
          }else{
            if(undefined !== activeZones[i].keyRange){
              td.innerHTML = "lo:"+activeZones[i].keyRange.lo+", hi:"+activeZones[i].keyRange.hi;
            }
          }
          if(1 == countRows){
            td.setAttribute("style", "margin: 0 6px; padding:3px; height: 183px; text-align: center;");
          }else{
            td.setAttribute("style", "margin: 0 6px; padding:3px; height: 92px; text-align: center;");
          }
        break;
        case 2: //Generators
          if(undefined !== activeZones[i].zones){
            obj = activeZones[i].zones[0].mergedGenerators;
          }else{
            obj = activeZones[i].mergedGenerators;
          }
          for (key in obj) {
            let tdId = "sf2gen_"+i;
            let str = document.createElement("div");
            str.setAttribute("style", "display:flex;");

            let substr1 = document.createElement("p");
            substr1.innerHTML = key;
            substr1.setAttribute("style", "display:block;width:125px;margin:0;line-height: normal;cursor:pointer;");
            substr1.setAttribute("onclick", `getInfoPrmSF('generators','${key}','${obj[key]}', '${tdId}')`);

            let substr2 = document.createElement("p");
            substr2.innerHTML = obj[key];
            substr2.setAttribute("style", "display:block;margin:0;line-height: normal;");

            str.appendChild(substr1); str.appendChild(substr2);
            td.id = tdId;
            td.appendChild(str);
          }
          if(1 == countRows){
            td.setAttribute("style","display:block;overflow:auto;text-align:left;line-height:normal;height:183px;margin:0;padding:3px;");
          }else{
            td.setAttribute("style","display:block;overflow:auto;text-align:left;line-height:normal;height:92px;margin:0;padding:3px;");
          }
        break;
        case 3: //Modulators
          if(undefined !== activeZones[i].zones){
            obj = activeZones[i].zones[0].modulators;
          }else{
            obj = activeZones[i].modulators;
          }
          let keys = Object.keys(obj);
          if(0 !== keys.length){
            for (key in obj[keys[0]].source) {
              let tdId = "sf2mod_"+i;
              let str = document.createElement("div");
              str.setAttribute("style", "display:flex;");

              let substr1 = document.createElement("p");
              substr1.innerHTML = key;
              substr1.setAttribute("style", "display:block;width:60px;margin:0;line-height: normal;cursor:pointer;");
              substr1.setAttribute("onclick", `getInfoPrmSF('modulators','${key}','${obj[keys[0]].source[key]}', '${tdId}')`);

              let substr2 = document.createElement("p");
              substr2.innerHTML = obj[keys[0]].source[key];
              substr2.setAttribute("style", "display:block;margin:0;line-height: normal;");

              str.appendChild(substr1); str.appendChild(substr2);
              td.id = tdId;
              td.appendChild(str);
            }
          }
          if(1 == countRows){
            td.setAttribute("style","line-height:normal;overflow:auto;text-align:left;height:183px;width:80px;margin: 0 6px;padding:3px;");
          }else{
            td.setAttribute("style","line-height:normal;overflow:auto;text-align:left;height:92px;width:80px;margin: 0 6px;padding:3px;");
          }
        break;
        case 4: //Sample
          if(undefined !== activeZones[i].zones){
            obj = activeZones[i].zones[0].sample.header;
          }else{
            obj = activeZones[i].sample.header;
          }
          for (key in obj) {
            let str = document.createElement("div");
            str.setAttribute("style", "display:flex;");

            let tdId = "sf2smpl_"+i;
            let substr1 = document.createElement("p");
            substr1.innerHTML = key;
            substr1.setAttribute("style", "display:block;width:85px;margin:0;line-height: normal;cursor:pointer;");
            substr1.setAttribute("onclick", `getInfoPrmSF('sample','${key}', '${obj[key]}', '${tdId}')`);

            let substr2 = document.createElement("p");
            substr2.innerHTML = obj[key];
            substr2.setAttribute("style", "display:block;margin:0;line-height: normal;width: 75px;white-space: nowrap;");

            str.appendChild(substr1); str.appendChild(substr2);
            td.id = tdId;
            td.appendChild(str);
          }
          if(1 == countRows){
            td.setAttribute("style","display:block;overflow:auto;text-align:left;line-height:normal;height:183px;margin:0;padding:3px;");
          }else{
            td.setAttribute("style","display:block;overflow:auto;text-align:left;line-height:normal;height:92px;margin:0;padding:3px;");
          }
        break;
        case 5: //curNote
          td.innerHTML = "curNote: "+curNote;
          if(1 == countRows){
            td.setAttribute("style", "margin: 0 6px; height: 183px; text-align: center;");
          }else{
            td.setAttribute("style", "margin: 0 6px; height: 92px; text-align: center;");
          }
      }
      row.appendChild(td);
    }
    tblBody.appendChild(row);
  }

  //loader off
  let loader3 = document.getElementsByClassName("loader3");
  if(undefined !== loader3[0]) sf2viewer.removeChild(loader3[0]);

  return true;
}
function infoFileSF(){
  let standard = document.getElementById("standardMidi").querySelector(`webaudio-switch[name=standard][value='1']`);
  let descr_ul  = document.getElementById("descr_ul");
  let img_ahdsr = document.getElementById("img_ahdsr");
  let valStandard = document.getElementById(standard.id).getAttribute("soundfonts");
  valStandard = valStandard.split("|");

  img_ahdsr.style.display = "none";
  descr_ul.style.display = "block";
  descr_ul.setAttribute("style", "margin: 0px;padding:0 5px;line-height: 1.0;font-size:14px;color:black;font-family: 'Arial, Helvetica, sans-serif'");
  descr_ul.innerHTML = "fileName: "+valStandard[0]+"<br>size: "+valStandard[1]+"<br>last modified: "+valStandard[2]+"<br>";

  let banks_presets_hd = document.createElement("div");
  banks_presets_hd.setAttribute("style", "display:flex;height:16px;width:100%;");

  let banks_hd = document.createElement("label");
  banks_hd.setAttribute("style", "height:16px;width:30%;text-align: center;border: 1px solid black;");
  banks_hd.innerHTML = "Banks";
  banks_presets_hd.appendChild(banks_hd);

  let presets_hd = document.createElement("label");
  presets_hd.setAttribute("style", "height:16px;width:70%;text-align: center;border: 1px solid black;");
  presets_hd.innerHTML = "Presets";
  banks_presets_hd.appendChild(presets_hd);

  descr_ul.appendChild(banks_presets_hd);

  let banks_presets = document.createElement("div");
  banks_presets.setAttribute("style", "display:flex;height:187px;width:100%;background:white;");

  let banks = document.createElement("div");
  banks.id = "banks";
  banks.setAttribute("style", "display:flex;flex-direction: column;height:187px;width:30%;border: 1px solid black;overflow: auto;");
  banks_presets.appendChild(banks);

  let presets = document.createElement("div");
  presets.id = "presets";
  presets.setAttribute("style", "display:flex;flex-direction: column;height:187px;width:70%;border: 1px solid black;overflow: auto;");
  banks_presets.appendChild(presets);

  descr_ul.appendChild(banks_presets);

  let obj = soundFont.banks;
  for (key in obj) {
    let bank = document.createElement("p");
    bank.id = "sf2bank_"+key;
    bank.innerHTML = key;
    bank.setAttribute("style", "display:block;width:100%;margin:0;cursor:pointer;text-align: center;");
    bank.setAttribute("onclick", `getInfoPrmSF('banks','${key}','', 'banks')`);
    banks.appendChild(bank);
  }
  getInfoPrmSF('banks',curBank,'', 'banks');
}
/**
 * [setSynthProgNameSF description]
 * let filteredPreset = item.presets.filter(element => element !== null);
 */
function setSynthProgNameSF(){
  let progSFnames = [];

  soundFont.banks.forEach(function(bank, index){
    let presets = bank.presets;
    presets.forEach(function(preset, idx){
      if(undefined == progSFnames[index]) progSFnames[index] = [];
      progSFnames[index].push({"idx": idx, "namePreset": preset.header.name});
    });
  });
  synth.setProgNameSF(progSFnames);
  // console.log("progSFnames",progSFnames);
}
/**
 * [installSoundFonts description]
 * @param {[type]} fileNameSF [description]
 * @param {[type]} contentSF  [description]
 */
function installSoundFonts(fileNameSF, contentSF){
  let itemSelSF = document.getElementById(standMidi);
  let sf2Name = itemSelSF.getAttribute("soundfonts").split("|");

  //Init midiSynth for SoundFonts - have to create a Uint8Array first
  const buffer = new Uint8Array(contentSF);

  soundFont  = new SoundFont2(buffer);
  fileNameSF = sf2Name[0];

  setSynthProgNameSF(curBank);
  drawMetaDataSF2();

  let dataNote = soundFont.getKeyData(curBank, curProg, curNote);
  let preset = dataNote.preset;
  let activeZones = getActiveZones(preset, curNote);

  inform_panel.style.color = "#A0A378";
  inform_panel.innerHTML = "Install " + " ["+fileNameSF+"]";

  document.getElementById("editorBtn").removeAttribute("disabled");
  document.getElementById("graphBtn").removeAttribute("disabled");
  document.getElementById("sequencerBtn").removeAttribute("disabled");

  return activeZones;
}
function drawMetaDataSF2(){
  let metaDataSF = soundFont.metaData;

  ctxGraph.fillStyle = "#C3C3C3";
  ctxGraph.beginPath();
  ctxGraph.fillRect(720, 2, 258, 304);
  ctxGraph.fill();

  ctxGraph.fillStyle = "#37474F";
  ctxGraph.textAlign = "left";
  ctxGraph.font = "bold 16px sans-serif";

  ctxGraph.fillText("MetaData of SoundFonts", 725, 15);

  let posY = 15;
  let arrMetaData = Object.entries(metaDataSF);


  for (let [key, value] of arrMetaData) {
    posY += 18 ;

    if(undefined !== value && 18 <= value.length){
      let subStr1 = value.substr(0, 18).replace(/\r?\n|\r/g, '');
      let subStr2 = value.substr(18, value.length).replace(/\r?\n|\r/g, '');

      ctxGraph.font = "bold 14px sans-serif";
      ctxGraph.fillText(key+":", 725, posY);

      ctxGraph.font = "normal 14px sans-serif";
      ctxGraph.fillText(subStr1, 835, posY);
      ctxGraph.fillText(subStr2, 725, posY+18);

      posY += 18;
    }else{
      ctxGraph.font = "bold 14px sans-serif";
      ctxGraph.fillText(key+":", 725, posY);

      ctxGraph.font = "normal 14px sans-serif";
      ctxGraph.fillText(value, 835, posY);
    }
  }
  //imgs
  document.getElementById("canvas_imgs").style.display = "none";
}
