<template>
  <div class="login-wrapper">
    <div class="ui middle aligned center aligned grid">
      <div class="column">
        <h2 class="ui blue image header">
          <div class="content">
            Login
          </div>
        </h2>
        <form class="ui large form" id="loginform" @submit.prevent="submit">
          <div class="ui stacked segment">
            <div class="field">
              <div class="ui left icon input">
                <i class="user icon"></i>
                <input v-focus type="text" name="username" placeholder="Username" v-model="credentials.username" required>
              </div>
            </div>
            <div class="field">
              <div class="ui left icon input">
                <i class="lock icon"></i>
                <input type="password" name="password" placeholder="Password" v-model="credentials.password" required>
              </div>
            </div>
            <button type="submit" class="ui fluid large blue submit button">Login</button>
          </div>

          <div class="ui info message" v-if="loading">
            <icon name="refresh" spin></icon>&nbsp;&nbsp;
            Loggig you in...
          </div>

          <div class="ui error message" v-if="error" style="display: block;">
            {{ error }}
          </div>

        </form>
      </div>
    </div>
  </div>
</template>

<script>
  import auth from '../auth'
  import router from '../router'

  export default {
    data () {
      return {
        credentials: {
          username: '',
          password: ''
        },
        error: '',
        loading: false
      }
    },

    beforeMount () {
      // Check if the user is already logged in, if so, redirect him to the homepage
      if (auth.user.authenticated) {
        router.push({name: 'home'})
      }
    },

    methods: {
      submit () {
        this.loading = true
        this.error = ''
        var credentials = {
          username: this.credentials.username,
          password: this.credentials.password
        }

        auth.login(this, credentials, 'home')
      }
    }
  }
</script>

<style scoped>
  .image {
    margin-top: -100px;
  }

  .column {
    max-width: 450px;
  }

  .error.message {
    display: block;
  }

  .login-wrapper {
    background: url("../../static/bg.jpg") no-repeat center;
    background-size: cover;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    padding-top: 5em;
  }
</style>
