const { insertEtudiant } = require('../Models/Etudiants')
const { database } = require('../database')
const { URL } = require('./Config')
const dayjs = require('dayjs')

const getEtudiants = async () => {
  const XHR = new XMLHttpRequest()
  const allEtudiants = await database.prepare('SELECT * FROM etudiants').all()

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

      let numInscArray = []
      for (let index = 0; index < allEtudiants.length; index++) {
        numInscArray.push(allEtudiants[index].num_inscription)
      }

      database.transaction(() => {
        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]['status'],
              etudiantFromWeb[index]['num_inscription'],
              etudiantFromWeb[index]['mention_id']
            )
          } else {
            const getTheEtudiant = database
              .prepare('SELECT * FROM etudiants WHERE id = ?')
              .get(etudiantFromWeb[index]['id'])

            if (getTheEtudiant.updated_at < etudiantFromWeb[index]['updated_at']) {
              database
                .prepare(
                  'UPDATE etudiants SET nom = ?, prenom = ?, photos = ?, date_de_naissances = ?, niveau = ?, annee_scolaire = ?, status = ?, mention_id = ?, num_inscription = ? WHERE id = ?'
                )
                .run(
                  etudiantFromWeb[index]['nom'],
                  etudiantFromWeb[index]['prenom'],
                  etudiantFromWeb[index]['photos'],
                  etudiantFromWeb[index]['date_de_naissances'],
                  etudiantFromWeb[index]['niveau'],
                  etudiantFromWeb[index]['annee_scolaire'],
                  etudiantFromWeb[index]['status'],
                  etudiantFromWeb[index]['num_inscription'],
                  etudiantFromWeb[index]['mention_id'],
                  etudiantFromWeb[index]['id']
                )
            }
          }
        }
      })()
    } else {
      console.log('impossible de contacter le server')
    }
  }

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

async function getAll() {
  await getEtudiants()
}

module.exports = {
  getAll
}
