<template>
  <v-container fill-height>
    <v-layout align-center justify-center>
      <v-dialog v-model="registerDialog" class="pa-4" max-width="30%">
        <register-dialog @registered="registered($event)"/>
      </v-dialog>
      <v-flex text-xs-center xs8 sm6 md4 lg2>
        <img v-if="production" :src="productionBrandUrl"/>
        <img v-else src="../assets/brand.png"/>
        <h3 class="pt-3">Log in</h3>
        <v-alert
          outline
          v-if="msg"
          color="error"
          :value="true"
          transition="fade-transition"
        >{{ msg }}</v-alert>
        <p v-else>But I corrected them, sir.</p>
        <v-form
          @submit.prevent="submit">
          <v-text-field
            label="Username"
            v-model="credentials.username"
            required
            autofocus
          />
          <v-text-field
            label="Password"
            v-model="credentials.password"
            type="password"
            required
          />
          <v-layout class="btn-container">
            <v-btn @click="registerDialog = true" id="register">Register</v-btn>
            <v-btn :loading="loading" type="submit" color="primary">Access</v-btn>
          </v-layout>
        </v-form>
      </v-flex>
    </v-layout>
  </v-container>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import RegisterDialog from '@/components/RegisterDialog'
import { Authentication as Auth } from '@/store/modules/authentication'

export default {
  components: { RegisterDialog },
  name: 'grady-login',
  data () {
    return {
      credentials: {
        username: '',
        password: ''
      },
      registerDialog: false,
      loading: false
    }
  },
  computed: {
    msg () { return Auth.state.message },
    userRole () { return Auth.state.user.role },
    production () {
      return process.env.NODE_ENV === 'production'
    },
    productionBrandUrl () {
      return `https://${window.location.host}/static/img/brand.png`
    }
  },
  methods: {
    submit () {
      this.loading = true
      Auth.getJWT(this.credentials).then(() => {
        return Promise.all([
          Auth.getUser(),
          Auth.getJWTTimeDelta()
        ])
      }).then(() => {
        this.$router.push({ name: 'home' })
        this.loading = false
      }).catch((err) => {
        let msg = "Login failed. Please try again."
        if (typeof err === "string") {
          msg = err
        }

        Auth.SET_MESSAGE(msg)
        this.loading = false
      })
    },
    registered (credentials) {
      this.registerDialog = false
      this.credentials.username = credentials.username
      this.credentials.password = credentials.password
      Auth.SET_MESSAGE('Your account is being activated. Please wait.')
    }
  }
}
</script>

<style scoped>
  .v-btn {
    margin: 0px;
  }

  .btn-container {
    display: flex;
    flex-wrap: nowrap;
    justify-content: space-around;
  }
</style>