// here the data from the local and web server become one for etudiants table

/**
 * our get and insert etudiants function, don't touch it
 */
const { getAllEtudiants, insertEtudiant } = require('../Models/Etudiants')

/**
 * URL fro the server web, you can modify it like your Domain name
 */
const { URL } = require('./Config')

/**
 * function to get the all etudiants
 *
 * @returns promise
 */
async function getAllEtudiantsFetch() {
  const etudiants = await getAllEtudiants()

  return etudiants
}

async function verifyEtudiantTableWeb() {
  /**
   * class AJAX, don't touch it
   */
  const XHR = new XMLHttpRequest()

  let etudiants = await getAllEtudiantsFetch()

  XHR.onreadystatechange = () => {
    if (XHR.readyState === 4) {
      if (XHR.status === 200) {
        // nothing here because the statement is in the server web
      } else {
        console.log('impossible de contacter le server pour la syncronisation')
      }
    }
  }

  const data = new FormData()

  data.append('Verification', JSON.stringify(etudiants))

  XHR.open('POST', `${URL}/verifywebEtudiants`, true)
  XHR.setRequestHeader('x-requested-with', 'xmlhttprequest')
  XHR.send(data)
}

async function verifyTableLocalEtudiants() {
  /**
   * class AJAX, don't touch it
   */
  const XHR = new XMLHttpRequest()
  let etudiants = await getAllEtudiantsFetch()

  XHR.onreadystatechange = () => {
    if (XHR.readyState === 4) {
      if (XHR.status === 200) {
        const etudiantFromWeb = JSON.parse(XHR.responseText)

        // set all email from base local in Array numInscArray
        let numInscArray = []
        for (let index = 0; index < etudiants.length; index++) {
          numInscArray.push(etudiants[index]['num_inscription'])
        }

        // search if the email from user from server is in local or not
        // if not, then insert it
        for (let index = 0; index < etudiantFromWeb.length; index++) {
          if (numInscArray.includes(etudiantFromWeb[index]['num_inscription']) === false) {
            insertEtudiant(
              etudiantFromWeb[index]['nom'],
              etudiantFromWeb[index]['prenom'],
              etudiantFromWeb[index]['photos'],
              etudiantFromWeb[index]['date_de_naissances'],
              etudiantFromWeb[index]['niveau'],
              etudiantFromWeb[index]['annee_scolaire'],
              etudiantFromWeb[index]['num_inscription']
            )
          }
        }
      } else {
        console.log('impossible de contacter le server pour la syncronisation')
      }
    }
  }

  XHR.open('GET', `${URL}/verifylocalEtudiants`, true)
  XHR.setRequestHeader('x-requested-with', 'xmlhttprequest')
  XHR.send()
}

// Call both functions sequentially or in parallel as needed
async function synchronizeDataEtudiants() {
  try {
    await verifyEtudiantTableWeb()
    await verifyTableLocalEtudiants()
  } catch (error) {
    console.error('Error during synchronization:', error)
  }
}

module.exports = {
  synchronizeDataEtudiants
}
