const m = require('mithril')
const Authentication = require('./authentication')
const api = require('./api')
const Input = require('./input')
const lang = require('./lang')
const videos = require('./videos')

const Login = {
  oninit: function(vnode) {
    this.redirect = vnode.attrs.redirect || ''
    Authentication.requiresNotLogin()

    this.error = ''
    this.form = {
      email: '',
      password: '',
    }
  },

  loginuser: function(vnode, e) {
    e.preventDefault()
    this.error = ''

    if (!this.form.email) this.error = lang.login_missing_email // Email is missing
    if (!this.form.password) this.error = lang.login_missing_password // Password is missing

    if (this.error) return false

    api.sendRequest({
      method: 'POST',
      url: '/api/authentication/login',
      body: this.form,
    })
    .then((result) => {
      if (!result.token) return Promise.reject(new Error(lang.login_error_auth)) // Unknown error from server. Try again later
      Authentication.updateToken(result.token)
      m.route.set(this.redirect || '/')
      videos.refreshTree()
    })
    .catch((error) => {
      this.error = lang.format(lang.login_error, error.message) // Error while logging in:
      this.form.password = ''
    })

    return false
  },

  view: function(vnode) {
    return [
      m('div.page.page-login', [
        m('div.modal', [
          m('form', {
            onsubmit: this.loginuser.bind(this, vnode),
          }, [
            m('h3', lang.header_title /* Filadelfia archival center */),
            this.error ? m('p.error', this.error) : null,
            m(Input, {
              label: lang.login_email, // Email or name
              form: this.form,
              formKey: 'email',
            }),
            m(Input, {
              label: lang.login_password, // Password
              type: 'password',
              form: this.form,
              formKey: 'password',
            }),
            m('input.spinner', {
              hidden: api.loading,
              type: 'submit',
              value: lang.login_submit, // Log in
            }),
            api.loading ? m('div.loading-spinner') : null,
          ]),
        ]),
        m('footer', lang.mformat(
            lang.unsplash, // Photo by X on Y
            m('a', { href: 'https://unsplash.com/@franhotchin?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash', target: '_blank' }, 'Francesca Hotchin'),
            m('a', { href: 'https://unsplash.com/photos/landscape-photo-of-mountain-covered-with-snow-FN-cedy6NHA?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash', target: '_blank' }, 'Unsplash'),
        )),
      ]),
    ]
  },
}

module.exports = Login
