let currentVideoPath = null;

/*

Functions used in the setup or affect most of the gui

*/
//For managing the displaying of the costum document section
var showCDValue = 0;
function showCD() {
  try {
    if(showCDValue == 0){
      document.getElementById('cdContainer').style.display = "block";
      document.getElementById('helpContainer').style.display = "none";
      document.getElementById('step1').style.display ="none";
      document.getElementById('step2').style.display ="none";
      document.getElementById('step3').style.display ="none";
      document.getElementById('step4').style.display ="none";
      document.getElementById('step5').style.display ="none";
      document.getElementById('step6').style.display ="none";
      showCDValue = 1;
      showHelpValue = 0;
    } else {
      currentStep = 1;
      showCDValue = 0;
      document.getElementById('cdContainer').style.display = "none";
      showStep(1);
    }
  } catch (error) {
    console.log(error)
  }
  
}

var showHelpValue = 0;
function showHelp() {
  try {
    if(showHelpValue == 0){
      document.getElementById('helpContainer').style.display = "flex";
      document.getElementById('cdContainer').style.display = "none";
      document.getElementById('step1').style.display ="none";
      document.getElementById('step2').style.display ="none";
      document.getElementById('step3').style.display ="none";
      document.getElementById('step4').style.display ="none";
      document.getElementById('step5').style.display ="none";
      document.getElementById('step6').style.display ="none";
      showHelpValue = 1;
    } else {
      currentStep = 1;
      showHelpValue = 0;
      showCDValue = 0;
      document.getElementById('helpContainer').style.display = "none";
      showStep(1);
    }
  } catch (error) {
    console.log(error)
  }
  
}

//language changing feature => changes the language of every displayed text
function changeLanguage(language) {
  try {
    document.getElementById('labelKI').textContent = languageOptions[language].labelKI;
    document.getElementById('labelTranscription').textContent = languageOptions[language].labelTranscription;
    document.getElementById('labelLanguage').textContent = languageOptions[language].labelLanguage;
    document.getElementById('title').textContent = languageOptions[language].title;
    document.getElementById('h1').textContent = languageOptions[language].h1;
    document.getElementById('p1').textContent = languageOptions[language].p1;
    document.getElementById('fileName').textContent = languageOptions[language].fileName;
    document.getElementById('manualUploadBtn').textContent = languageOptions[language].manualUploadBtn;
    document.getElementById('label_format').textContent = languageOptions[language].label_format;
    document.getElementById('label_summary').textContent = languageOptions[language].label_summary;
    document.getElementById('label_summary_result').textContent = languageOptions[language].label_summary_result;
    document.getElementById('label_summary_note').textContent = languageOptions[language].label_summary_note;
    document.getElementById('submitButton').textContent = languageOptions[language].submitButton;
    document.getElementById('step_nav1').textContent = languageOptions[language].step_nav1;
    document.getElementById('step_nav2').textContent = languageOptions[language].step_nav2;
    document.getElementById('step_nav3').textContent = languageOptions[language].step_nav3;
    document.getElementById('step_nav4').textContent = languageOptions[language].step_nav4;
    document.getElementById('step_nav5').textContent = languageOptions[language].step_nav5;
    document.getElementById('step_nav6').textContent = languageOptions[language].step_nav6;
    document.getElementById('labelSpeaker').textContent = languageOptions[language].labelSpeaker;
    document.getElementById('labelSpeakerAudio').textContent = languageOptions[language].labelSpeakerAudio;
    document.getElementById('labelSpeakerWriter').textContent = languageOptions[language].labelSpeakerWriter;
    document.getElementById('speakerLocker').textContent = languageOptions[language].speakerLocker;
    document.getElementById('speakerResender').textContent = languageOptions[language].speakerResender;
    document.getElementById('downloadButton').textContent = languageOptions[language].downloadButton;
    document.getElementById('box1_p1').textContent = languageOptions[language].box1_p1;
    document.getElementById('box2_p2').textContent = languageOptions[language].box2_p2;
    document.getElementById('box3_p3').textContent = languageOptions[language].box3_p3;
    document.getElementById('labelType').textContent = languageOptions[language].labelType;

    document.getElementById('customDocBtn').textContent = languageOptions[language].customDocBtn;
    document.getElementById('cd_h1').textContent = languageOptions[language].cd_h1;
    document.getElementById('cd_existingDocs').textContent = languageOptions[language].cd_existingDocs;
    document.getElementById('cd_docName').textContent = languageOptions[language].cd_docName;
    document.getElementById('docName').placeholder = languageOptions[language].docName;
    document.getElementById('cd_promt').textContent = languageOptions[language].cd_promt;
    document.getElementById('prompt').placeholder = languageOptions[language].prompt;
    document.getElementById('goBackBtn').textContent = languageOptions[language].goBackBtn;
    document.getElementById('deleteBtn').textContent = languageOptions[language].deleteBtn;
    document.getElementById('generateBtn').textContent = languageOptions[language].generateBtn;
    document.getElementById('newDoc').textContent = languageOptions[language].newDoc;

    document.getElementById("step1_h2").textContent = languageOptions[language].step1_h2;
    document.getElementById("step2_h2").textContent = languageOptions[language].step2_h2;
    document.getElementById("step3_h2").textContent = languageOptions[language].step3_h2;
    document.getElementById("step4_h2").textContent = languageOptions[language].step4_h2;
    document.getElementById("step5_h2").textContent = languageOptions[language].step5_h2;
    document.getElementById("step6_h2").textContent = languageOptions[language].step6_h2;

    document.getElementById("back_btn").textContent = languageOptions[language].back_btn;
    document.getElementById("help_page_h1").textContent = languageOptions[language].help_page_h1;
    document.getElementById("help_page_tableofcontents").textContent = languageOptions[language].help_page_tableofcontents;
    document.getElementById("hp_convertVid").textContent = languageOptions[language].hp_convertVid;
    document.getElementById("hp_firstStep").textContent = languageOptions[language].hp_firstStep;
    document.getElementById("hp_secondStep").textContent = languageOptions[language].hp_secondStep;
    document.getElementById("hp_thirdStep").textContent = languageOptions[language].hp_thirdStep;
    document.getElementById("hp_fourthStep").textContent = languageOptions[language].hp_fourthStep;
    document.getElementById("hp_fifthStep").textContent = languageOptions[language].hp_fifthStep;
    document.getElementById("hp_sixthStep").textContent = languageOptions[language].hp_sixthStep;
    document.getElementById("hp_createDoc").textContent = languageOptions[language].hp_createDoc;
    document.getElementById("hp_editDoc").textContent = languageOptions[language].hp_editDoc;
    document.getElementById("hp_deleteDoc").textContent = languageOptions[language].hp_deleteDoc;
    document.getElementById("hp_convertVid_h2").textContent = languageOptions[language].hp_convertVid_h2;
    document.getElementById("hp_firstStep_h3").textContent = languageOptions[language].hp_firstStep_h3;
    document.getElementById("hp_secondStep_h3").textContent = languageOptions[language].hp_secondStep_h3;
    document.getElementById("hp_thirdStep_h3").textContent = languageOptions[language].hp_thirdStep_h3;
    document.getElementById("hp_fourthStep_h3").textContent = languageOptions[language].hp_fourthStep_h3;
    document.getElementById("hp_fifthStep_h3").textContent = languageOptions[language].hp_fifthStep_h3;
    document.getElementById("hp_sixthStep_h3").textContent = languageOptions[language].hp_sixthStep_h3;
    document.getElementById("hp_createDoc_h2").textContent = languageOptions[language].hp_createDoc_h2;
    document.getElementById("hp_editDoc_h2").textContent = languageOptions[language].hp_editDoc_h2;
    document.getElementById("hp_deleteDoc_h2").textContent = languageOptions[language].hp_deleteDoc_h2;
    document.getElementById("hp_firstStep_p").textContent = languageOptions[language].hp_firstStep_p;
    document.getElementById("hp_secondStep_p").textContent = languageOptions[language].hp_secondStep_p;
    document.getElementById("hp_thirdStep_p").textContent = languageOptions[language].hp_thirdStep_p;
    document.getElementById("hp_fourthStep_p").textContent = languageOptions[language].hp_fourthStep_p;
    document.getElementById("hp_fifthStep_p").textContent = languageOptions[language].hp_fifthStep_p;
    document.getElementById("hp_sixthStep_p").textContent = languageOptions[language].hp_sixthStep_p;
    document.getElementById("hp_createDoc_p").textContent = languageOptions[language].hp_createDoc_p;
    document.getElementById("hp_editDoc_p").textContent = languageOptions[language].hp_editDoc_p;
    document.getElementById("hp_deleteDoc_p").textContent = languageOptions[language].hp_deleteDoc_p;
    

  } catch (error) {
    console.log("Error in script.js changeLanguage function");
    console.log(error);
  }

}

/*

Functions used for the step navigation

*/

//Step-navigation
const steps = document.querySelectorAll(".step");
const stepButtons = document.querySelectorAll(".step-item");
let currentStep = 1;
const totalSteps = steps.length;

function showStep(stepNumber) {
  if(showCDValue == 1){
    showCDValue = 0;
    document.getElementById('cdContainer').style.display = "none";
  }
  if(showHelpValue == 1){
    showHelpValue = 0;
    document.getElementById('helpContainer').style.display = "none";
  }
  if (stepNumber < 1 || stepNumber > totalSteps) {
    console.error("StepNumber out of Bounds", stepNumber);
    return;
  }
  steps.forEach(step => step.style.display = "none");
  document.getElementById("step" + stepNumber).style.display = "flex";

  stepButtons.forEach(btn => btn.classList.remove("active"));
  document.querySelector(`.step-item[data-step="${stepNumber}"]`).classList.add("active");
  const activeBtn = document.querySelector(`.step-item[data-step="${stepNumber}"]`);

  if (activeBtn) activeBtn.classList.add("active");

  prevBtn.disabled = stepNumber == 1;
  nextBtn.disabled = stepNumber === totalSteps;
  currentStep = stepNumber;
}

/*

Functions used in Step 1

*/

//function to display the file path in the drop down box
function handleFiles(files) {
  try {
    if (files.length > 0) {
      const file = files[0];
      if (file.type.startsWith('video/')) {
        const filePath = window.explorer.onFileDrop(files[0])
        videoUpload.files = files;
        fileName.textContent = `Chosen video: ${file.name}`;
        currentVideoPath = filePath;
        generateThumbnail(filePath);
        activateSubmitBtn(true);
      }
    }
  } catch (error) {
    console.log("Error in script.js handleFiles function");
    console.log(error);
  }

}

//Video thumbnail generation. Shows a scene from the selected video file as a preview
function generateThumbnail(path) {
  try {
    const videoElement = document.getElementById("previewThumbnail");
    while (videoElement.firstChild) videoElement.removeChild(videoElement.firstChild);
    videoElement.src = path;
    videoElement.type = "video/mov";
    videoElement.load();
    videoElement.style.maxWidth = 40;
    videoElement.style.maxHeight = 40;
    videoElement.autoplay = false;
  } catch (error) {
    console.log("Error in the generateThumbnail function in the script.js file \n");
    console.log(error);
  }

}



/*

Functions used in Step 2

*/

//function to load ai options to the drop down list
function loadAiOptions(options) {
  try {
    var menu = document.getElementById('ai_type');
    var object_holdy;
    var choice;
    object_holdy = options
    for (i = 0; i < options.length; i++) {
      choice = document.createElement('option');
      choice.textContent = object_holdy[i].displayname;
      choice.value = object_holdy[i].name;
      menu.appendChild(choice);
    }
  } catch (error) {
    console.log("Error in script.js loadAiOptions function");
    console.log(error);
  }
}

//function to load transcription options to the drop down list
function loadTranscriptionOptions(options) {
  try {
    var menu = document.getElementById('transkript_type');
    var object_holdy;
    var choice;
    object_holdy = options
    for (i = 0; i < options.length; i++) {
      choice = document.createElement('option');
      choice.textContent = object_holdy[i].displayname;
      choice.value = object_holdy[i].name;
      menu.appendChild(choice);
    }
  } catch (error) {
    console.log("Error in script.js function loadTranscriptionOptions");
    console.log(error);
  }
}

//function to load data type options to the drop down list
function loadDataTypeOptions(options) {
  try {
    var menu = document.getElementById('output_type');
    var object_holdy;
    var choice;
    object_holdy = options
    for (i = 0; i < options.length; i++) {
      choice = document.createElement('option');
      choice.textContent = object_holdy[i].displayname;
      choice.value = object_holdy[i].name;
      menu.appendChild(choice);
    }
  } catch (error) {
    console.log("Error in script.js function loadDataTypeOptions");
    console.log(error);
  }
}

//function to load language options to the drop down list
function loadLanguageOptions() {
  try {

    var menu = document.getElementById('language_option');
    var menu_doc = document.getElementById('document_language_option');
    var object_holdy;
    var choice;
    var choice2;
    object_holdy = Object.keys(languageOptions);
    for (i = 0; i < object_holdy.length; i++) {
      choice = document.createElement('option');
      choice.textContent = object_holdy[i];
      choice.value = object_holdy[i];
      choice.setAttribute('data-image', languageOptions[object_holdy[i]].flagPath);
      choice2 = document.createElement('option');
      choice2.textContent = object_holdy[i];
      choice2.value = object_holdy[i];
      choice2.setAttribute('data-image', languageOptions[object_holdy[i]].flagPath);
      menu_doc.appendChild(choice2);
      menu.appendChild(choice);
      
    }
    new lc_select(document.getElementById('language_option'));    //loads the flag images so they get displayed in the gui
    new lc_select(document.getElementById('document_language_option'));
  } catch (error) {
    console.log("Error in script.js loadLanguageOptions function");
    console.log(error);
  }
}



/*

Functions used in Step 3

*/



/*

Functions used in Step 4

*/

//function to check if one checkbox is at least clicked. Final controll function before sending the input to the generation
function checkBoxes() {
  try {
    const checkboxes = document.querySelectorAll('input[name="docFormat"]');
    let isChecked = false;
    var checkedCounter = 0;
    checkboxes.forEach(function (checkbox) {
      if (checkbox.checked) {
        isChecked = true;
        checkedCounter++;
      }
    });

    if (isChecked) {
      //Code to submit the video
      var selectedCheckboxes = {};
      checkboxes.forEach(function (checkbox) {
        if (checkbox.checked) {
          selectedCheckboxes[checkbox.nextElementSibling.textContent] = "";
        }
      });

      const testEndings = [".mp4", ".mov", ".avi", ".mkv"];
      var pathTest = window.electronAPI.getFilePath(videoUpload.files[0]);
      var pathToLower = pathTest.toLowerCase();
      if (testEndings.some(e => pathToLower.endsWith(e))) {
        //assembly of the json for the main

        var typeCheckbox;
        if (document.getElementById("docFormat").checked) typeCheckbox = document.getElementById("docFormat").value;
        if (document.getElementById("docFormatSummary1").checked) typeCheckbox = document.getElementById("docFormatSummary1").value;
        if (document.getElementById("docFormatSummary2").checked) typeCheckbox = document.getElementById("docFormatSummary2").value;
        if (document.getElementById("docFormatSummary3").checked) typeCheckbox = document.getElementById("docFormatSummary3").value;
        if (document.getElementById("docFormatCustom").checked) typeCheckbox = document.getElementById("docFormatCustom").value;

        document.getElementById("testy").style.visibility = "visible"
        document.getElementById("box1").style.backgroundColor = "red";
        document.getElementById("box2").style.backgroundColor = "red";
        document.getElementById("box3").style.backgroundColor = "red";
        document.getElementById("box4").style.backgroundColor = "red";
        console.log(selectedCheckboxes);
        const outputType = document.getElementById("output_type");
        const transcriptionType = document.getElementById("transkript_type");
        const aiType = document.getElementById("ai_type");
        const docLanguage = document.getElementById("document_language_option");
        const sendingPackage = {
          "video": {
            "module": "extraction-video-to-audio",
            "inputVideoPath": pathTest
          },
          "transcription": {
            "module": transcriptionType.value
          },
          "document": {
            "module": aiType.value,
            "type": typeCheckbox,
            "outputType": outputType.value,
            "outputLanguage": docLanguage.value
          }
        };
        console.log(docLanguage.value);
        window.submit.submit(sendingPackage)
      } else {
        alert('The given file is not compatible. These are the available types: [".mp4", ".mov", ".avi", ".mkv"].');
      }


    } else {
      //language only english at the moment
      alert('Please select at least one document type.');
    }
  } catch (error) {
    console.log("Error in script.js checkBoxes function");
    console.log(error);
  }

}

//function the the submit button on step 4 can be pressed
function activateSubmitBtn(hasFile) {
  try {
    document.getElementById("submitButton").disabled = !hasFile;
  } catch (error) {
    console.log(error);
  }
}

//function to regulate the progress on the progressbar
function updateProgressBar(bar, value) {
  try {
    value = Math.round(value);
    bar.querySelector(".progress_fill").style.width = `${value}%`;
    bar.querySelector(".progress_text").textContent = `${value}%`;
  } catch (error) {
    console.log("Error in scripts.js updateProgressBar function");
    console.log(error);
  }

}

//function to hide the progressbar
function deaktivateProgressbar() {
  try {
    document.getElementById("progressbar").style.visibility = "hidden";
  } catch (error) {
    console.log(error);
  }
}

/*

Functions used in Step 5

*/


//function to load speaker options to the drop down list
function loadSpeakerOptions(options) {
  try {
    var menu = document.getElementById('cur_speaker');
    var l = document.getElementById('cur_speaker').options.length - 1;
    for (i = l; i >= 0; i--) {
      menu.remove(i);
    }
    var object_holdy;
    var choice;
    object_holdy = Object.keys(options);
    for (i = 0; i < object_holdy.length; i++) {
      choice = document.createElement('option');
      choice.textContent = options[object_holdy[i]].name;
      choice.value = object_holdy[i];
      menu.appendChild(choice);
    }
    document.getElementById("speakerAudioViewer").src = options.speakerA.src;
  } catch (error) {
    console.log("Error in script.js loadSpeakerOptions function");
    console.log(error);
  }
}

//function to load speaker audio file options to the drop down list
function loadSpeakerAudio(option) {
  try {
    var menu = document.getElementById('speakerAudioViewer');
    var aud = document.createElement("source");
    aud.src = options;
    menu.appendChild(aud);
  } catch (error) {
    console.log("Error in script.js loadSpeakerAudio function");
    console.log(error);
  }
}

//Audio value setter
var speakerAudios = {};
var speakerEndValues = {};
function setSpeakerAudiosValue(valy) {
  try {
    speakerAudios = valy;
    speakerRewriten = valy;
    document.getElementById("speakerAudioViewer").src = valy.speakerA.src;
  } catch (error) {

  }
}
//Function to rewrite the speaker name in the json
function rewriteSpeakerName() {
  try {
    const select = document.getElementById("cur_speaker");
    const newName = document.getElementById("newSpeaker").value.trim();

    if (!newName) {
      alert("Please enter a new speaker name");
      return;
    }

    const selectedIndex = select.selectedIndex;
    const selectedValue = select.value;

    // Update speakerAudios data
    speakerAudios[selectedValue].name = newName;

    // Update the specific option text and keep value
    select.options[selectedIndex].text = newName;
    select.options[selectedIndex].value = selectedValue;

    // Keep it selected
    select.selectedIndex = selectedIndex;

    console.log("Speaker renamed:", newName);
  } catch (error) {
    console.log("Error renaming speaker:", error);
  }
}

/*

Functions for Step 6

*/

function fileDownload() {
  try {
    window.download.file_download();
  } catch (error) {
    console.error("Download failed:", error);
  }
}

/*

Functions for the custom document section

*/

//reload drop down
function reloadDocuments() {
  try{
    [...existingDocs.querySelectorAll('option:not([value="newDoc"])')]
      .forEach(o => o.remove());
    [...customDocumentTypes.querySelectorAll('option:not([value="newDoc"])')]
      .forEach(o => o.remove());

    window.api.getTxtFiles().then(files => {
      files.forEach(file => {
        var option = document.createElement('option');
        option.value = file;
        option.textContent = file
          .replace('.txt', '')          // Endung entfernen
          .replace(/_/g, ' ')           // Leerzeichen ersetzen
          .replace(/\b\w/g, c => c.toUpperCase()); // ersten Buchstaben groß
        existingDocs.appendChild(option);
        var option2 = document.createElement('option');
        option2.value = file;
        option2.name = file;
        option2.textContent = file
          .replace('.txt', '')          // Endung entfernen
          .replace(/_/g, ' ')           // Leerzeichen ersetzen
          .replace(/\b\w/g, c => c.toUpperCase()); // ersten Buchstaben groß
        customDocumentTypes.appendChild(option2);
      });
    });
  }
  catch(error){
    console.log(error)
  }
  
}

function sendSpeakerPackages() {
  try {
    window.submitSpeaker.speaker_submit(speakerAudios);
  } catch (error) {
    console.log(error);
  }
}

window.sendSpeakerPackages = sendSpeakerPackages;

/*

Functions for the help page

*/

//Function to show the dropdown list in the help page
function toggleTOC() {
  try {
    document.getElementById("toc").classList.toggle("show");
  } catch (error) {
    console.log(error)
  }
}

//Function to hide the dropdown list in the help page
function closeTOC() {
  try {
    document.getElementById("toc").classList.remove("show");
  } catch (error) {
    console.log(error)
  }
}