// reusable ajax promise
const ajaxRequest = obj => {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: obj.url,
      type: obj.type,
      headers: obj.headers,
      data: JSON.stringify(obj.body),
      beforeSend: (xhr, settings) => {
      }, success: (response, textStatus, jqXHR) => {
        resolve(response)
      }, error: (jqXHR, textStatus, errorThrown) => {
        reject({
          status: textStatus,
          message: `Error making request`,
          request: obj
        })
      }
    })
  })

}

// http request
const httpRequest = {
  login(params) {
    return ajaxRequest({
      url: 'http://172.16.2.53:8080/security-rest/api/user/login',
      type: 'POST',
      headers: {
        "Content-type": 'application/json',
        "Accept": 'application/json'
      },
      body: params
    })
  },
  verify() {
    return ajaxRequest({
      url: 'http://172.16.2.53:8080/security-rest/api/user/verificarLogin',
      type: 'POST',
      headers: {
        "Content-type": 'application/json',
        "Accept": 'application/json',
//        "Authorization": window.localStorage.getItem('Authorization')
        "Authorization": Cookies.get('Authorization')
      }
    })
  }
}

// domevents
const DOMEvents = {
  init() {
    this.signIn()
    this.verify()
  },
  signIn() {
    document.querySelector('#signIn').addEventListener('click', (e) => {
      let params = {
        usuario: document.querySelector('#usuario').value.trim(),
        pass: document.querySelector('#pass').value,
        codigoProyecto: "2",
        path: `${location.origin}/${location.pathname.split('/')[1]}/`
      }

      httpRequest.login(params)
        .then(data => {
          if (data.status) {
            delete data["status"]
//            window.localStorage.setItem('Authorization', 'Bearer ' + data.token)
//            window.localStorage.setItem('menu', JSON.stringify(data.menu))
            Cookies.set('Authorization', `Bearer ${data.token}`, {expiry: 36000000})
            Cookies.set('menu', `${JSON.stringify(data.menu)}`)
            window.location.href = 'main.jsp'

          } else {
            alert('No tienes autorización')
          }
          console.log(data)
        })
        .catch(err => console.log(err))
    })
  },
  verify() {
    document.querySelector('#verify').addEventListener('click', (e) => {
      httpRequest.verify()
        .then(data => console.log(data))
        .catch(err => console.log(err))
    })
  }
}


DOMEvents.init()