<template>
  <nav>
    <b-modal :active="ajaxErrorModal" @update:active="value => ajaxErrorModal = value" :width="640" scroll="keep" style="z-index:  200">
      <div class="modal-card" style="width: auto">
        <header class="modal-card-head">
          <p class="modal-card-title">Something went wrong...</p>
          <button
              type="button"
              class="delete"
              @click="$emit('close')"/>
        </header>
        <section class="modal-card-body media">
          <p :key='error' v-for='error in this.$store.state.errors.errors' style='margin: 1rem;'>{{error}}</p>
        </section>
        <footer class="modal-card-foot">
          <b-button
              label="Got it"
              @click="$emit('close')" />
        </footer>
      </div>
    </b-modal>
    <b-modal :active="loginModal" @update:active="value => loginModal = value" :width="640" scroll="keep">
      <b-form>
        <div class="modal-card" style="width: auto">
          <header class="modal-card-head">
            <p class="modal-card-title">Login to Kaverti</p>
            <button
                type="button"
                class="delete"
                @click="$emit('close')"/>
          </header>
          <section class="modal-card-body">
            <b-field label="Username or Email">
              <b-input
                  :value="login.username"
                  v-model="login.username"
                  placeholder="Your username or email"
                  required>
              </b-input>
            </b-field>

            <b-field label="Password">
              <b-input
                  type="password"
                  :value="login.password"
                  v-model="login.password"
                  password-reveal
                  placeholder="Your password"
                  required>
              </b-input>
            </b-field>
          </section>
          <footer class="modal-card-foot">
            <b-button
                label="Close"
                @click="$emit('close')" />
            <b-button
                @click="doLogin()"
                label="Login"
                :loading="login.loading"
                type="is-primary" />
            <b-button
                @click="registerModal = true; loginModal = false"
                label="Need an account?"
                type="is-success" />
          </footer>
        </div>
      </b-form>
    </b-modal>
    <b-modal :active="registerModal" @update:active="value => registerModal = value" :width="640" scroll="keep">
      <b-form>
        <div class="modal-card" style="width: auto">
          <header class="modal-card-head">
            <p class="modal-card-title">Register to Kaverti</p>
            <button
                type="button"
                class="delete"
                @click="$emit('close')"/>
          </header>
          <section class="modal-card-body">
            <b-field label="Username">
              <b-input
                  :value="register.username"
                  v-model="register.username"
                  placeholder="Your username or email"
                  required>
              </b-input>
            </b-field>
            <b-field label="Email">
              <b-input
                  type="email"
                  :value="register.email"
                  v-model="register.email"
                  placeholder="Your username or email"
                  required>
              </b-input>
            </b-field>
            <b-field label="Password">
              <b-input
                  type="password"
                  :value="register.password"
                  v-model="register.password"
                  password-reveal
                  placeholder="Your password"
                  required>
              </b-input>
            </b-field>
            <b-field label="Password Confirmation">
              <b-input
                  type="password"
                  :value="register.confirm"
                  v-model="register.confirm"
                  password-reveal
                  placeholder="Your password"
                  required>
              </b-input>
            </b-field>
            <b-checkbox v-model="register.agree">I agree to the <router-link to="/legal/tos">Terms of Service</router-link></b-checkbox>
          </section>
          <footer class="modal-card-foot">
            <b-button
                label="Close"
                @click="$emit('close')" />
            <b-button
                @click="doRegister()"
                label="Register"
                :loading="register.loading"
                type="is-primary" />
            <b-button
                @click="registerModal = false; loginModal = true"
                label="Have an account?"
                type="is-success" />
          </footer>
        </div>
      </b-form>
    </b-modal>
    <b-navbar>
      <template #brand>
        <b-navbar-item tag="router-link" :to="{ path: '/' }">
          <img
              src="https://cdn.kaverti.com/logo.png"
              alt="Kaverti Logo"
          >
        </b-navbar-item>
      </template>
      <template #start>
        <b-navbar-item href="#">
          Home
        </b-navbar-item>
        <b-navbar-item href="#">
          Documentation
        </b-navbar-item>
        <div v-if="$store.state.debug" class="navbar-item has-dropdown is-hoverable is-info">
          <a class="navbar-link">
            <p>Developer Options</p>
          </a>
          <div class="navbar-dropdown">
            <b-navbar-item tag="router-link" to="/debug">Debug Page</b-navbar-item>
            <b-navbar-item @click="fakeUser()">Fake User</b-navbar-item>
          </div>
        </div>
      </template>

      <template #end>
        <b-navbar-item v-if="!$store.state.user.username" tag="div">
          <div class="buttons">
            <b-button @click="registerModal = true" class="button is-primary">
              <strong>Register</strong>
            </b-button>
            <b-button @click="loginModal = true" class="button is-light">
              Log in
            </b-button>
          </div>
        </b-navbar-item>
        <b-navbar-item v-if="$store.state.user.username">
          <div class="navbar-item has-dropdown is-hoverable is-info">
            <a class="navbar-link">
              <p>{{$store.state.user.username}}</p>
            </a>
              <div class="navbar-dropdown">
              <b-navbar-item tag="router-link" :to="'/u/' + $store.state.user.username">My profile</b-navbar-item>
              <b-navbar-item tag="router-link" to="/settings">Settings</b-navbar-item>
              <b-navbar-item tag="router-link" to="/transactions">Transactions</b-navbar-item>
              <b-navbar-item tag="router-link" to="/character">My Avatar</b-navbar-item>
              <b-navbar-item tag="router-link" to="/downloads">Downloads</b-navbar-item>
              <b-navbar-item @click="fakeUser()">Logout</b-navbar-item>
            </div>
          </div>
        </b-navbar-item>
      </template>
    </b-navbar>
  </nav>
</template>
<script>
import AjaxErrorHandler from '../../assets/js/errorHandler'
import axios from "axios";
export default {
  data() {
    return {
      loginModal: false,
      registerModal: false,
      login: {
        username: '',
        password: '',
        loading: false
      },
      register: {
        username: '',
        email: '',
        password: '',
        confirm: '',
        agree: false,
        loading: false
      }
    }
  },
  computed: {
    ajaxErrorModal: {
      get() {
        return this.$store.state.errors.modal
      },
      set(val) {
        this.$store.commit('setAjaxErrorsModalState', val)
      }
    },
  },
  methods: {
    doRegister() {
      this.register.loading = true
      this.axios.post('/api/v1/users/register', {
        username: this.register.username,
        password: this.register.password,
        email: this.register.email,
        confirm: this.register.confirm,
        agree: this.register.agree
      }).then((res) => {
        this.register.loading = false
        this.$store.commit('setUsername', res.data.username)
        this.$store.commit('setAvatar', res.data.avatar)
        this.$store.commit('setID', res.data.id)
        this.$store.commit('setEmailVerified', res.data.emailVerified)
        this.$store.commit('setEmail', res.data.email)
        this.$store.commit('setAdmin', res.data.admin)
        this.$store.commit('setToken', res.data.token)
      }).catch(e => {
        this.register.loading = false

        AjaxErrorHandler(this.$store)(e, (error, errors) => {
          let path = error.path

          if (this.errors[path] !== undefined) {
            this.errors[path] = error.message
          } else {
            errors.push(error.message)
          }
        })
      })
    },
    doLogin() {
      this.login.loading = true
      this.axios.post('/api/v1/users/login', {
        username: this.login.username,
        password: this.login.password
      }).then((res) => {
        this.login.loading = false
        this.$store.commit('setToken', res.data.token)
        localStorage.setItem('token', JSON.stringify(res.data.token));
        Object.assign(axios.defaults, {headers: {Authorization: this.$store.state.user.token}})
      }).catch(e => {
        this.login.loading = false

        AjaxErrorHandler(this.$store)(e, (error, errors) => {
          let path = error.path

          if (this.errors[path] !== undefined) {
            this.errors[path] = error.message
          } else {
            errors.push(error.message)
          }
        })
      })
    },
    fakeUser () {
      this.$store.commit('fakeUser')
      this.$buefy.snackbar.open(`WARNING: You have fake authenticated, you do not have authenticated API access. Use for debug purposes only.`)
      Object.assign(axios.defaults, {headers: {Authorization: this.$store.state.user.token}})
    }
  }
}
</script>