const m = require('mithril')
const Authentication = require('./authentication')
const api = require('./api')

const Login = {
  oninit: function(vnode) {
    this.redirect = vnode.attrs.redirect || ''
    if (Authentication.currentUser) return m.route.set('/')

    this.error = ''
    this.loading = false
    this.username = ''
    this.password = ''
  },

  oncreate: function() {
    if (Authentication.currentUser) return
  },

  loginuser: function(vnode, e) {
    e.preventDefault()
    if (!this.username) {
      this.error = 'Email is missing'
    } else if (!this.password) {
      this.error = 'Password is missing'
    } else {
      this.error = ''
    }
    if (this.error) return

    this.loading = true

    api.sendRequest({
      method: 'POST',
      url: '/api/authentication/login',
      body: {
        email: this.username,
        password: this.password,
      },
    })
    .then((result) => {
      if (!result.token) {
        return Promise.reject(new Error('Server authentication down.'))
      }
      Authentication.updateToken(result.token)
      m.route.set(this.redirect || '/')
    })
    .catch((error) => {
      this.error = 'Error while logging into NFP! ' + error.message
      vnode.state.password = ''
    })
    .then(() => {
      this.loading = false
      m.redraw()
    })
  },

  view: function(vnode) {
    return [
      m('div.wrapper', [
        this.loading ? m('div.loading-spinner') : null,
        m('div.login--first'),
        m('form.inside.login', {
          hidden: this.loading,
          onsubmit: this.loginuser.bind(this, vnode),
        }, [
          m('div.title', 'NFP.moe login'),
          this.error ? m('div.error', this.error) : null,
          m('label', 'Email or name'),
          m('input', {
            type: 'text',
            value: this.username,
            oninput: (e) => { this.username = e.currentTarget.value },
          }),
          m('label', 'Password'),
          m('input', {
            type: 'password',
            value: this.password,
            oninput: (e) => { this.password = e.currentTarget.value },
          }),
          m('input', {
            type: 'submit',
            value: 'Log in',
          }),
        ]),
        m('div.login--asuna.spritesheet'),
      ]),
    ]
  },
}

module.exports = Login
