/*

Listeners for the program setup and changes

*/

//Listener for when the gui has been loaded so it can fill the dop down menus in step 2 and the language options
window.addEventListener('load', async (e) => {
  try {
    loadLanguageOptions();
    const value = await window.onStartup.getModuleNames();
    loadAiOptions(value.ai_modules);
    loadTranscriptionOptions(value.transcription_modules);

  } catch (error) {
    console.log("Error in the window listener load in the renderer.js \n");
    console.log(error);
  }
});

//Listener if the language of the displayed text's in the gui should be changed 
language_option.addEventListener('change', (e) => {
  try {
    const select = document.getElementById('language_option');
    changeLanguage(select.value);
  } catch (error) {
    console.log("Error in the language_option change listener in the renderer.js");
    console.log(error);
  }
});

stepButtons.forEach(btn => {
  btn.addEventListener("click", () => {
    try {
      const step = parseInt(btn.dataset.step);
      showStep(step);
    } catch (error) {
      console.log(error);
    }
  });
});

//Listener if the button to change the current step to the previus one is pressed
prevBtn.addEventListener("click", () => {
  try {
    if (currentStep > 1) showStep(currentStep - 1);
  } catch (error) {
    console.log(error);
  }
});

//Listener if the button to change the current step to the next one is pressed
nextBtn.addEventListener("click", () => {
  try {
    if (currentStep < totalSteps) showStep(currentStep + 1);
  } catch (error) {
    console.log(error);
  }
});

/*

Listeners for Step 1

*/

//Listener if a file has been draged over the drop down field
uploadContainer.addEventListener("dragover", (e) => {
  try {
    e.stopPropagation();
    e.preventDefault();
  } catch (error) {
    console.log("Error in renderer.js dragover listener function")
  }
});

//listener for when a file get dropped on the drag&drop field
uploadContainer.addEventListener("drop", (e) => {
  try {
    e.stopPropagation()
    e.preventDefault()
    const files = e.dataTransfer.files
    const filePath = window.explorer.onFileDrop(files[0])
    const testEndings = [".mp4", ".mov", ".avi", ".mkv"];
    var pathToLower = filePath.toLowerCase();
    if (testEndings.some(e => pathToLower.endsWith(e))) {
      const files1 = e.dataTransfer.files;
      handleFiles(files1);
    } else {
      alert('The given file is not compatible. These are the available types: [".mp4", ".mov", ".avi", ".mkv"].');
    }
  } catch (error) {
    console.log("Error in renderer.js with the listerner for the drop function");
    console.log(error);
  }
});

//listener for the file explorer search when something got selected
videoUpload.addEventListener("change", () => {
  try {
    if (videoUpload.files.length > 0) {
      const file = videoUpload.files;
      handleFiles(file);
    }
  } catch (error) {
    console.log(error);
  }
});

//listener for the file explorer search
manualUploadBtn.addEventListener('click', () => {
  try {
    videoUpload.click();
  } catch (error) {
    console.log("Error in manualBtn EventListener click");
    console.log(error);
  }

});

/*

Listeners for Step 2

*/

/*

Listeners for Step 3

*/

//Checkboxlistener so that only one checkbox can be selected at a time
docFormat.addEventListener("change", (e) => {
  try {
    if (docFormat.checked) {
      docFormatSummary1.checked = false;
      docFormatSummary2.checked = false;
      docFormatSummary3.checked = false;
      docFormatCustom.checked = false;
    }
  } catch (error) {
    console.log(error)
  }
});
//Checkboxlistener so that only one checkbox can be selected at a time
docFormatSummary1.addEventListener("change", (e) => {
  try {
    if (docFormatSummary1.checked) {
      docFormat.checked = false;
      docFormatSummary2.checked = false;
      docFormatSummary3.checked = false;
      docFormatCustom.checked = false;
    }
  } catch (error) {
    console.log(error)
  }
});
//Checkboxlistener so that only one checkbox can be selected at a time
docFormatSummary2.addEventListener("change", (e) => {
  try {
    if (docFormatSummary2.checked) {
      docFormatSummary1.checked = false;
      docFormat.checked = false;
      docFormatSummary3.checked = false;
      docFormatCustom.checked = false;
    }
  } catch (error) {
    console.log(error)
  }
});
//Checkboxlistener so that only one checkbox can be selected at a time
docFormatSummary3.addEventListener("change", (e) => {
  try {
    if (docFormatSummary3.checked) {
      docFormatSummary1.checked = false;
      docFormatSummary2.checked = false;
      docFormat.checked = false;
      docFormatCustom.checked = false;
    }
  } catch (error) {
    console.log(error)
  }
});
//Checkboxlistener so that only one checkbox can be selected at a time
docFormatCustom.addEventListener("change", (e) => {
  try {
    if (docFormatCustom.checked) {
      docFormatSummary1.checked = false;
      docFormatSummary2.checked = false;
      docFormatSummary3.checked = false;
      docFormat.checked = false;
    }
  } catch (error) {
    console.log(error)
  }
});

/*

Listeners for Step 4

*/

//Functions for the displayed progress in the progressbar so it can be changed out of the main process
window.electron.progress((event, arg) => {
  try {
    if (arg.curstep == 1) {
      setCircleOne();
    } else if (arg.curstep == 2) {
      setCircleZwo();
    } else if (arg.curstep == 3) {
      setCircleThree();
    } else if (arg.curstep == 4) {
      setCircleFour();
    }
  } catch (error) {
    console.log(error)
  }
});

//All for are for setting the corresponding progress section to green (or red)
function setCircleOne() {
  try {
    if (document.getElementById("box1").style.backgroundColor == "green") {
      document.getElementById("box1").style.backgroundColor = "red";
    } else {
      document.getElementById("box1").style.backgroundColor = "green";
    }
  } catch (error) {
    console.log(error)
  }
};
function setCircleZwo() {
  try {
    if (document.getElementById("box2").style.backgroundColor == "green") {
      document.getElementById("box2").style.backgroundColor = "red";
    } else {
      document.getElementById("box2").style.backgroundColor = "green";
    }
  } catch (error) {
    console.log(error)
  }
};
function setCircleThree() {
  try {
    if (document.getElementById("box3").style.backgroundColor == "green") {
      document.getElementById("box3").style.backgroundColor = "red";
    } else {
      document.getElementById("box3").style.backgroundColor = "green";
    }
  } catch (error) {
    console.log(error)
  }
};
function setCircleFour() {
  try {
    if (document.getElementById("box4").style.backgroundColor == "green") {
      document.getElementById("box4").style.backgroundColor = "red";
    } else {
      document.getElementById("box4").style.backgroundColor = "green";
    }
  } catch (error) {
    console.log(error)
  }
};

/*

Listeners for Step 5

*/

//Speaker change listener, changes the previewed audio snippet
cur_speaker.addEventListener("change", (e) => {
  try {
    document.getElementById("speakerAudioViewer").src = speakerAudios[document.getElementById("cur_speaker").value].src;
  } catch (error) {
    console.log(error)
  }
});

//Function so the main process can give the gui a json with the speakers and their audio
window.audios.speakerAudios((event, arg) => {
  try {
    loadSpeakerOptions(arg);
    setSpeakerAudiosValue(arg);
  } catch (error) {
    console.log(error)
  }
});

/*

Listeners for the costum documents section

*/

//Listener for closing the custom document section again
goBackBtn.addEventListener("click", () => {
  try {
    showCD();
  } catch (error) {
    console.log(error)
  } 
});

//Listener for the save button in the custom document section
generateBtn.addEventListener("click", () => {
  try {
    const name = docName.value.trim();
    const content = document.getElementById("prompt").value.trim();
    if (!name || !content) {
      result.textContent = "Bitte Dokumentname und Prompt ausfüllen.";
      setTimeout(() => {
        result.textContent = "";
      }, 3000);
      return;
    }
    window.api.saveTxtFile(name, content).then();
    result.textContent = "Dokument erfolgreich gespeichert!";
    setTimeout(() => {
      result.textContent = "";
    }, 3000);
    reloadDocuments(); 
  } catch (error) {
    console.log(error)
  }
});

//Used for deleting documents in the costum document section
deleteBtn.addEventListener("click", () => {
  try {
    const name = docName.value.trim();

    if (!name) {
      result.textContent = "Bitte Dokumentname angeben.";
      setTimeout(() => {
        result.textContent = "";
      }, 3000);
      return;
    }
    var success = true;
    window.api.deleteTxtFile(name).then((success) => {
      if (success) {
        result.textContent = "Dokument erfolgreich gelöscht!";
        reloadDocuments();
        existingDocs.dispatchEvent(new Event("change"));
      } else {
        result.textContent = "Dokument konnte nicht gelöscht werden.";
      } 
    });
  } catch (error) {
    console.log(error)
  }
});


//function to load existingDoc options to the drop down list
window.api.getTxtFiles().then(files => {
  try {
    reloadDocuments(); 
  } catch (error) {
    console.log(error)
  }
});

//Shows the content inside the big textarea inside the costume dokument section
existingDocs.addEventListener("change", async () => {
  try {
    const existingDocsed = existingDocs.value;
    const exampleText = "";
    if (existingDocsed === "newDoc") {
      docNameWrapper.classList.remove("hidden");
      docName.value = "";
      document.getElementById("prompt").value = exampleText;
      document.getElementById("prompt").textContent = exampleText;
      return;
    }
    docNameWrapper.classList.add("hidden");
    document.getElementById("prompt").textContent = "";
    document.getElementById("prompt").value = "";

    const content = await window.api.readTxtFile(existingDocsed);
    document.getElementById("prompt").value = content;
    document.getElementById("prompt").textContent = content;
    docName.value = existingDocsed.replace(".txt", "");
  } catch (error) {
   console.log(error) 
  }
  
});

/*

Listeners for the help page

*/

//For the help page dropdown list
document.addEventListener("click", function (e) {
  try {
    const toc = document.getElementById("toc");
    const toggle = document.querySelector(".toc-toggle");

    if (!toc.contains(e.target) && !toggle.contains(e.target)) {
        toc.classList.remove("show");
    }
  } catch (error) {
    console.log(error);
  }
});
