const fs = require('fs');
const cheerio = require('cheerio');
const Swal = require('sweetalert2')
const encode = require('./encode')
const path = require('path')
require('dotenv').config();


//Get the value from .env
const isEncrypted = process.env.ENCRYPTED;

// start the Autosave filename take the names in xml folder
////////
function getFilesInFolder(folderName) {
  const xmlFilePath = path.join(__dirname, folderName);
  try {
    const fileNames = fs.readdirSync(xmlFilePath);
    const xmlFiles = fileNames.filter((file) => file.endsWith('.xml'));
    return xmlFiles;
  } catch (error) {
      console.error('Error reading folder:', error);
      return [];
    }
}
//XmlPath get from .env
const xmlPath_ = process.env.XML_FILE_PATH;
const folderName = `/${xmlPath_}`;
const filePaths = [];
const files = getFilesInFolder(folderName);
files.forEach((file) => {
  const filePath = file;
  filePaths.push(filePath);
});
////////
//end the autosave

  function saveXmlToFile(xmlData, filePath,reorder=false, xmlfilename, jsonData, jsonfilePath) {
    // console.log(xmlData);
    // console.log(filePath);
    // Check if the file path is provided
    if (!filePath) {
      console.error('File path is required.');
      return;
    }
  
    // Write the XML data to the specified file path
    fs.writeFileSync(filePath, xmlData, 'utf8', (err) => {
      console.log("fs write inside ");
      alert("fs write inside")
      if (err) {
        console.error('Error writing XML file:', err);
      } else {
        console.log('XML file saved successfully.');
  
        // Clear all data in local storage
        localStorage.clear();
  
      }
    });

    if(jsonData !== ""){

     // Write the JSON data to the specified file path
    fs.writeFileSync(jsonfilePath, jsonData, 'utf8', (err) => {

      if (err) {
        console.error('Error writing XML file:', err);
      } else {
        console.log('JSON file saved successfully.');

        localStorage.clear();

      }
    }); 

    }
 


    localStorage.clear();
    if(reorder){
      window.location.reload();
    }else{
      window.location.href = 'addform.html?filename=' + xmlfilename;
      //  window.location.reload();
  
    }
    
    }


function savexml(UserFilename,reorder=false) {
  console.log("reorder",reorder);
  // Get the XML string from localStorage
  var xmlString = localStorage.getItem("xml");
  var jsonString = localStorage.getItem("Correct_Answer_Json");
  console.log('save json : ', jsonString);
  console.log('save xml : ', xmlString);

  //check Encrypted or not
  var enc = "";
  var encJson = "";
  if (isEncrypted === 'YES') {
    // Encrypt 
    enc = encode(xmlString);
    if(jsonString)
    {
      encJson = encode(jsonString);
    }
  } else {
    enc = xmlString;
    if(jsonString)
    {
      encJson = jsonString; 
    }
    
  }
  
  console.log('save xml : ', enc);

  //XmlPath get from .env 
  const xmlPathenv=process.env.XML_FILE_PATH;
  const xmlPath = path.join(__dirname, xmlPathenv)
  // Get the json string from localStorage for set fileName
  var jsonData = localStorage.getItem("json"); 

  // Create a filename using on the subtitle
  var xmlfilename = `${UserFilename}.xml`;
  var jsonfilename = `${UserFilename}_answer.json`;

  // file path where you want to save the XML file
  // const xmlfilePath = process.cwd() + `/${xmlPath}` + xmlfilename;

  const xmlfilePath = `${xmlPath}` + xmlfilename;
  const jsonfilePath = `${xmlPath}` + jsonfilename;
  // const jsonfilePath = process.cwd() + '/xml/' + jsonfilename;

  if(reorder){
    saveXmlToFile(enc, xmlfilePath,reorder=true, xmlfilename, encJson, jsonfilePath);
  }else{
    // Call the function to save the XML file
    saveXmlToFile(enc, xmlfilePath, false, xmlfilename, encJson, jsonfilePath);
  }
}


function promptBox() {

  var jsonData = localStorage.getItem("json");
  var jsonString = JSON.parse(jsonData);
  var getTitle = jsonString.question_paper_title;
  var RawFileNam = removeHtmlTags(getTitle);
  var RawFileName;

  if (RawFileNam === "" || RawFileNam === null) {
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = String(currentDate.getMonth() + 1).padStart(2, '0'); 
        const day = String(currentDate.getDate()).padStart(2, '0');
        let hours = currentDate.getHours();
        let ampm = 'AM';
        
        if (hours > 12) {
            hours -= 12;
            ampm = 'PM';
        }
        
        hours = String(hours).padStart(2, '0');
        const minutes = String(currentDate.getMinutes()).padStart(2, '0');

        // Create a formatted date-time string
        const formattedDateTime = `${year}${month}${day}(${hours};${minutes}${ampm})`;
         RawFileName = "untitled" +formattedDateTime;
  } else {
    RawFileName = RawFileNam
  }
  Swal.fire({
    title: 'Enter Filename',
    input: 'text',
    inputValue: RawFileName,
    showCancelButton: true,
    showDenyButton: false,
    denyButtonText: 'Overwrite',
    confirmButtonText: 'Submit',
    cancelButtonText: 'Cancel',
    inputValidator: (value) => {
      // console.log(value);
      const entervalue =value+'.xml'
      if (!value) {
        return 'You need to enter Filename!'
      }
      else if (value){

        const fileexist =fileexists(entervalue);
       if(fileexist){
        Swal.update({ showDenyButton: true });
        return 'This file Name already exists'
       }else {
        Swal.update({ showDenyButton: false }); 
      }
      }
    }
  }).then((result) => {
    // console.log(result);
    if (result.isConfirmed) {

      const inputValue = result.value
      savexml(inputValue)
    }else if(result.isDenied){
      savexml(RawFileName)
    }
  })


}

// function using for REMOVE HTML ELEMENT  in the String
function removeHtmlTags(inputString) {

  const $ = cheerio.load(inputString);
  const text = $.text();

  return text;
}

//check filename is already exists or not
function fileexists(enteredfilename) {
  var nextFilename
  for (const files of filePaths) {
    nextFilename = files;
    if (nextFilename === enteredfilename) {
      return true;
    }
    }
    
}
    
