<script setup lang="ts">
import { ref } from 'vue';
import { useTokenStore } from '@/stores/token';
import MessageBox from '@/components/MessageBox.vue';
import { webLogin as apiCommonWebLogin } from '@/api/common';
import { goToHome } from '@/router';

const isLoggingIn = ref<boolean>(false);
const username = ref<string>("");
const password = ref<string>("");

const messagebox = ref<InstanceType<typeof MessageBox> | null>(null);

const login = async () => {
  // disable UI first
  isLoggingIn.value = true;

  // // try get salt
  // if (ccn_api_common_salt(username)) {
  //     // continue login
  //     if (ccn_api_common_login(username, password)) {
  //         // ok, logged
  //         // jump into home page again
  //         window.location.href = '/web/home';
  //     } else ccn_messagebox_Show($.i18n.prop("ccn-i18n-js-fail-login"));
  // } else ccn_messagebox_Show($.i18n.prop("ccn-i18n-js-fail-login"));

  const token = await apiCommonWebLogin(username.value, password.value);
  if (typeof token !== 'undefined') {
    // OK. We have logged in.
    // Update token storage
    const tokenStore = useTokenStore();
    tokenStore.login(token);
    // Go to home page.
    goToHome();
  } else {
    // Show login error.
    messagebox.value?.show("Fail to login. Please check your username or password.");
  }

  // Enable all UI
  isLoggingIn.value = false;
}

</script>

<template>
  <div style="margin-top: 1.25rem; width: 100%; display: flex; justify-content: center; align-items: center;">
    <div class="card" style="padding: 1.25rem;">
      <div class="field">
        <label class="label">User Name</label>
        <div class="control has-icons-left has-icons-right">
          <input v-model="username" :disabled="isLoggingIn" class="input" type="text">
          <span class="icon is-small is-left">
            <font-awesome-icon icon="fas fa-user"></font-awesome-icon>
          </span>
        </div>
      </div>
      <div class="field">
        <label class="label">Password</label>
        <p class="control has-icons-left">
          <input v-model="password" :disabled="isLoggingIn" class="input" type="password">
          <span class="icon is-small is-left">
            <font-awesome-icon icon="fas fa-lock"></font-awesome-icon>
          </span>
        </p>
      </div>

      <div class="control">
        <button class="button is-primary" :disabled="isLoggingIn" @click="login">Login</button>
      </div>

    </div>
  </div>

  <MessageBox ref="messagebox"/>
</template>

<style scoped></style>
