<template>
  <div> {{loginString}} </div>
  <section class="login_modal">
    <div class="login_field">
      <label for="userName">Username: </label>
      <input
        type="text"
        id="login-username"
        v-model="username"
        required
        />
    </div>
    <div class="login_field">
      <label for="password">Password: </label>
      <input
        type="password"
        id="login-password"
        v-model="password"
        required
        />
    </div>
    <div class="login_field">
      <button
        type="button"
        id="loginButton"
        v-on:click="login()"
        >Login</button>

      <button
        type="button"
        id="logoutButton"
        v-on:click="logout()"
        >Logout</button>
    </div>

  </section>
</template>
<script lang="ts" setup>
const username = ref("")
const password = ref("")
const loginString = ref("not logged in")

const login = () => {
  new LoginHelper(username.value, password.value).login()
    .then((session)=>{
      console.log(session, "adding to storage")
      storage.AddSession(session)
      window.location.reload()
    }).catch((e)=>{
      if(e.code == "ERR_BAD_REQUEST") {
        alert("invalid username/password")
        return
      }
      alert("unknown error, please report")
      console.log(e)
    })
}

const logout = () => {
  new LogoutHelper().logout().then(()=>{
    storage.RemoveSession()
    localStorage.clear()
    window.location.reload()
  })
}

const s = storage.GetSession()
const api = new LTOApiv0(s)
if (s != undefined) {
  username.value = s.user
}

const updateLogin = () => {
  api.GetLoggedin().then((res)=>{
    if(res) {
      loginString.value = "logged in as " + s.user
    }
  })
}
updateLogin()


</script>

<script lang="ts">
import { defineComponent, computed, PropType, defineProps, defineEmits, ref} from 'vue';
import { LTOApiv0 } from '../lib/lifeto';
import { LoginHelper, LogoutHelper, Session } from '../lib/session';
import { storage } from '../session_storage';

</script>
