<template>
  <div class="apselui login">
    <div class="login__state">{{ state }}</div>
    <div class="login__users">
      <select 
        v-model=selectedUser :disabled="state != 'idle'">
        <option v-for="user in users" :value="user" v-bind:key="user.username">{{user.username}}</option>
      </select> <br />
    </div>
    <div class="login__actions">
      <button @click=login :disabled="state != 'idle'">Login</button> <br />
    </div>
    <div>
      {{error}}
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { AuthenticationApi, AuthenticateResult } from '@apsel/apsel-api-ts-axios';
import axios from 'axios';

@Component({
  components: {},
})
export default class Login extends Vue {
  public error = '';

  public users = [
    { username: 'admin@gmail.com', password: 'admin12345' },
    { username: 'dora@gmail.com', password: 'dora1234' },
  ];

  public selectedUser = this.users[0];

  /** the result of the authentication */
  public authentication: AuthenticateResult = {
    accessToken: '',
    refreshToken: '',
    userId: '',
    sessionId: '',
    anonymous: true,
  };

  /* internal state */
  private state = 'idle'; // loading | error | complete

  /* Change the state */
  public setState(state: string) {
    this.state = state;
  }

  /** Connect */
  public async login() {
    try {
        // First we need to log-in
      this.error = '';
      this.setState('login');
      const authApi = new AuthenticationApi({}, 'http://localhost:9000/', axios);
      const res = (await authApi.authenticate(this.selectedUser));
      if (res.status === 200) {
        this.authentication = res.data;
        this.setState('complete');
        this.$emit('login', this.authentication);
      } else {
        this.setState('idle');
        this.error = 'login failed';
        console.error('Login failed', res);
      }
    } catch (e) {
      this.setState('idle');
      this.error = e;
      console.error('Login failed', e);
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">


</style>
