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

/**
 * our get and insert users function, don't touch it
 */
const { getAllUsers, insertUser } = require('../Models/Users')

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

/**
 * function to get the all users
 *
 * @returns promise
 */
async function getAllUsersFetch() {
  const users = await getAllUsers()

  return users
}

/**
 * function to syncronise data from local to web server,
 * it will be an async function to get the result of promise in getAllUsersFetch() function
 */
async function verifyUserTableWeb() {
  /**
   * class AJAX, don't touch it
   */
  const XHR = new XMLHttpRequest()
  let users = await getAllUsersFetch()

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

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

async function verifyUserTableLocal() {
  /**
   * class AJAX, don't touch it
   */
  const XHR = new XMLHttpRequest()
  let users = await getAllUsersFetch()

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

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

        // search if the email from user from server is in local or not
        // if not, then insert it
        for (let index = 0; index < usersFromWeb.length; index++) {
          if (emailArray.includes(usersFromWeb[index]['email']) === false) {
            insertUser(
              usersFromWeb[index]['username'],
              usersFromWeb[index]['email'],
              usersFromWeb[index]['password'],
              usersFromWeb[index]['photos'],
              usersFromWeb[index]['roles']
            )
          }
        }
      } else {
        console.log('impossible de contacter le server pour la syncronisation')
      }
    }
  }

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

// Call both functions sequentially or in parallel as needed
async function synchronizeData() {
  try {
    setTimeout(await verifyUserTableWeb(), 2000)
    setTimeout(await verifyUserTableLocal(), 1000)
  } catch (error) {
    console.error('Error during synchronization:', error)
  }
}

module.exports = {
  synchronizeData
}
