<template>
  <FormDialog ref="main" buttonText="Login" @validated="doLogin">
    <v-card-title class="headline">
      Log In
    </v-card-title>

    <v-card-text>
      <v-text-field
        ref="autofocus"
        v-model="login"
        :rules="loginRules"
        label="User name"
        required
      ></v-text-field>

      <v-text-field
        v-model="password"
        :rules="passwordRules"
        :append-icon="showPassword ? 'visibility' : 'visibility_off'"
        @click:append="showPassword = !showPassword"
        :type="showPassword ? 'text' : 'password'"
        label="Password"
        required
      ></v-text-field>
    </v-card-text>
  </FormDialog>
</template>

<script>
import FormDialog from './FormDialog.vue'
import * as Cookies from 'js-cookie'
import axios from '@/plugins/axios'

export default {
  name: 'LoginForm',

  components: {
    FormDialog
  },

  data: () => ({
    login: '',
    loginRules: [v => !!v || 'Please enter user name'],

    password: '',
    showPassword: false,
    passwordRules: [v => !!v || 'Please enter password']
  }),

  methods: {
    doLogin() {
      axios
        .post('/user/login', {
          session: Cookies.get('session'),
          login: this.login,
          password: this.password
        })
        .then(response => {
          if (response.data.success) {
            let cookie_data = JSON.parse(response.data.message)
            Cookies.set('session', cookie_data.value, cookie_data.properties)
            this.$refs.main.showSnackbar('Login successful!', 'success')
            this.$router.push('usercp')
          } else {
            this.$refs.main.showSnackbar(response.data.message, 'error')
          }
        })
    }
  }
}
</script>
