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

const { getNoteOnline, insertNote } = require('../Models/Notes')

async function getAllNotesFeched() {
  const notes = await getNoteOnline()

  return notes
}

/**
 * send data to the database in the web
 */
async function verifyNoteToWeb() {
  /**
   * class AJAX, don't touch it
   */
  const XHR = new XMLHttpRequest()

  let notes = await getAllNotesFeched()

  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(notes))

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

async function verifyNoteToLocal() {
  /**
   * class AJAX, don't touch it
   */
  const XHR = new XMLHttpRequest()
  let notes = await getAllNotesFeched()

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

        let data_note = []
        // let bool = false;

        if (notes.length === 0) {
          // Case when local data is empty, insert all online data
          for (let index = 0; index < noteOnline.length; index++) {
            console.log(noteOnline[index]['etudiant_id'])
            insertNote(
              noteOnline[index].etudiant_id,
              noteOnline[index].etudiant_niveau,
              noteOnline[index].Algebre,
              noteOnline[index].Analyse,
              noteOnline[index].Mecanique_Generale_I,
              noteOnline[index].Resistance_Materiaux,
              noteOnline[index].Electricite,
              noteOnline[index].Chimie_Generale_1,
              noteOnline[index].Algorithmique,
              noteOnline[index].Thermodynamique_Physique,
              noteOnline[index].Mecanique_Fluide,
              noteOnline[index].Optique_Geometrique,
              noteOnline[index].Calcul_Numerique,
              noteOnline[index].Calcul_Vectoriel_Integral,
              noteOnline[index].Francais,
              noteOnline[index].Anglais,
              noteOnline[index].Dessin_Technique,
              noteOnline[index].Programmation
            )
          }
        } else {
          // Case when online data has more entries than local data
          // Loop through the notes array
          for (let index = 0; index < notes.length; index++) {
            // Push an object with the desired properties
            data_note.push({
              etudiant_id: notes[index].etudiant_id,
              etudiant_niveau: notes[index].etudiant_niveau
            })
          }
          for (let index = 0; index < noteOnline.length; index++) {
            let bool = true

            for (let jindex = 0; jindex < data_note.length; jindex++) {
              if (
                noteOnline[index].etudiant_id === data_note[jindex].etudiant_id &&
                noteOnline[index].etudiant_niveau === data_note[jindex].etudiant_niveau
              ) {
                bool = false
                break
              }
            }

            if (bool) {
              insertNote(
                noteOnline[index].etudiant_id,
                noteOnline[index].etudiant_niveau,
                noteOnline[index].Algebre,
                noteOnline[index].Analyse,
                noteOnline[index].Mecanique_General_I,
                noteOnline[index].Resistance_Materiaux,
                noteOnline[index].Electricite,
                noteOnline[index].Chimie_Generale_1,
                noteOnline[index].Algorithmique,
                noteOnline[index].Thermodynamique_Physique,
                noteOnline[index].Mecanique_Fluide,
                noteOnline[index].Optique_Geometrique,
                noteOnline[index].Calcul_Numerique,
                noteOnline[index].Calcul_Vectoriel_Integral,
                noteOnline[index].Francais,
                noteOnline[index].Anglais,
                noteOnline[index].Dessin_Technique,
                noteOnline[index].Programmation
              )
            }
          }
        }
      }
    }
  }

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

async function synchronizeDataNotes() {
  try {
    await verifyNoteToWeb()
    await verifyNoteToLocal()
  } catch (error) {
    console.error('Error during synchronization:', error)
  }
}

module.exports = {
  synchronizeDataNotes
}
