<template>
  <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">
        <div class="ui stacked segment">
          <div class="field">
            <div class="ui left icon input">
              <i class="user icon"></i>
              <input type="text" name="username" placeholder="Username" v-model="credentials.username">
            </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">
            </div>
          </div>
          <div class="ui fluid large blue submit button" @click="submit()">Login</div>
        </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>
</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>
  body {
    background-color: #efefef;
  }
  body > .grid {
    height: 100%;
  }
  .image {
    margin-top: -100px;
  }
  .column {
    max-width: 450px;
  }

  .error.message{
    display: block;
  }
</style>
