<template>
  <div>

    <button class="button" type="button" @click="showLogin = true">
      Login
    </button>

    <app-modal title="Login" :open="showLogin" @dismiss="showLogin = false">
      <div>
        <form @submit.prevent="login">

          <div v-if="error" class="notification is-danger">
            {{error}}
          </div>

          <div class="field">
            <label class="label">Username</label>
            <div class="control has-icons-left">
              <input class="input" type="text" placeholder="username" v-model="username">
              <app-icon icon="person" size="sm" class="is-left"></app-icon>
            </div>
          </div>

          <div class="field">
            <label class="label">Password</label>
            <div class="control has-icons-left">
              <input class="input" type="password" placeholder="password" v-model="password">
              <app-icon icon="lock-locked" size="sm" class="is-left"></app-icon>
            </div>
          </div>

          <div class="field is-grouped">
            <div class="control">
              <button type="submit" class="button is-primary" :disabled="!enableSubmit">Login</button>
            </div>
            <div class="control">
              <button class="button is-secondary" @click="showLogin = false">Cancel</button>
            </div>
          </div>

        </form>
      </div>
    </app-modal>

  </div>
</template>

<script>

  import AppModal from "./AppModal";
  import AppIcon from "./AppIcon";
  import api from "../lib/Api";
  import { mapMutations } from "vuex";

  export default {
    data() {
      return {
        showLogin: false,
        error: '',
        username: '',
        password: ''
      };
    },

    computed: {
      enableSubmit() {
        return this.username !== '' && this.password !== '' && !this.isLoading;
      }
    },

    methods: {
      ...mapMutations([
        'setUser'
      ]),

      login() {
        if (this.username !== '' && this.password != '') {
          this.loadResource(api.postLogin(this.username, this.password).then(data => {
            if (data.success) {
              this.setUser(data.user);
              this.showLogin = false;
            } else {
              this.error = data.message;
            }
          }));
        }
      }
    },

    components: {
      AppIcon,
      AppModal
    }
  }

</script>

<style lang="scss" scoped>
</style>