<template>
  <main>
  <router-view></router-view>
  </main>
</template>

<script>
  import ModalWindow from './components/ModalWindow'
  import NotFound from './views/pages/Page404'

  export default {
    name: 'app',
    components: {
      ModalWindow,
      NotFound
    },
    data () {
      return {
        kavelabelPosition: 'on-border',
        signup: {
          username: '',
          password: '',
          email: '',
          confirmPassword: '',
          passkey: '',

          loading: false,

          errors: {
            username: '',
            email: '',
            hash: '',
            confirmPassword: ''
          }
        },
        login: {
          username: '',
          password: '',

          loading: false,

          errors: {
            username: '',
            hash: ''
          }
        },
        loadingLogout: false,
        showMenu: false,
        ajaxErrorHandler: AjaxErrorHandler(this.$store)
      }
    },
    computed: {
      name () {
        return this.$store.state.meta.name
      },
      showAccountModal: {
        get () { return this.$store.state.accountModal },
        set (val) {
          this.$store.commit('setAccountModalState', val);
        }
      },
      showAjaxErrorsModal: {
        get () { return this.$store.state.ajaxErrorsModal },
        set (val) { this.$store.commit('setAjaxErrorsModalState', val) }
      },
      showAccountTab : {
        get () { return this.$store.state.accountTabs },
        set (index) { this.$store.commit('setAccountTabs', index) }
      },
      categories() {
        return this.$store.state.meta.categories
      }
    },
    methods: {
      recaptcha() {
        this.$recaptcha('login').then((token) => {
          console.log(token) // Will print the token
        })},
      showAccountModalTab (index) {
        this.toggleMenu()
        this.showAccountModal = true
        this.showAccountTab = index
      },
      toggleMenu () {
        this.showMenu = !this.showMenu
      },
      logout () {
        this.toggleMenu()
        this.loadingLogout = true
        this.axios.post(
                '/api/v1/user/' +
                this.$store.state.username +
                '/logout'

        ).then(res => {
          this.loadingLogout = false
          this.$store.commit('setUsername', '')
          this.$store.commit('setAdmin', res.data.admin)

          this.$socket.emit('accountEvent')

          this.$router.push('/')
        }).catch(err => {
          this.loadingLogout = false
          this.ajaxErrorHandler(err)
        })
      },
      botLogout (res) {
        this.loadingLogout = false
        this.$store.commit('setUsername', '')
        this.$store.commit('setAdmin', res.data.admin)

        this.$socket.emit('accountEvent')

        this.$router.push('/')
      },
      clearSignup () {
        this.signup.username = ''
        this.signup.password = ''
        this.signup.confirmPassword = ''
        this.signup.email = ''
        this.signup.passkey = ''

        this.$store.commit('setToken', null)
        this.$store.commit('setPassKey', null)
      },
      clearSignupErrors () {
        this.signup.errors.username = ''
        this.signup.errors.hash = ''
        this.signup.errors.confirmPassword = ''
        this.signup.errors.email = ''
        this.signup.errors.passkey = ''
      },
      clearLogin () {
        this.login.username = ''
        this.login.password = ''
      },
      clearLoginErrors () {
        this.login.errors.username = ''
        this.login.errors.hash = ''
      },
      closeAccountModal () {
        this.showAccountModal = false
        this.clearLogin()
        this.clearSignup()
        this.clearLoginErrors()
        this.clearSignupErrors()
      },
      createAccount () {
        this.clearSignupErrors()
        let postParams = {
          username: this.signup.username,
          password: this.signup.password,
          email: this.signup.email,
          passkey: this.signup.passkey
        }
        if(this.$store.state.token) {
          postParams.admin = true
          postParams.token = this.$store.state.token
        }
        if(this.$store.state.passkey) {
          postParams.passkey = this.$store.state.passkey
        }

        if(this.signup.password !== this.signup.confirmPassword) {
          this.signup.errors.confirmPassword = 'Passwords must match'
        } else {
          this.signup.loading = true

          this.axios.post(`/api/v1/passkey/${this.$store.state.passkey}`, postParams).then(res => {
            this.signup.loading = false
            this.$store.commit('setUsername', res.data.username)
            this.$store.commit('setAdmin', res.data.admin)
            this.closeAccountModal()

            this.$socket.emit('accountEvent')
          }).catch(e => {
            this.signup.loading = false

            this.ajaxErrorHandler(e, (error) => {
              let path = error.path

              if(this.signup.errors[path] !== undefined && this.signup.errors[path] !== undefined) {
                this.signup.errors[path] = error.message
              }
            })
          })
        }
      },
      doLogin () {
        this.clearSignupErrors()

        if(!this.login.username.trim().length) {
          this.login.errors.username = 'Username must not be blank'
          return
        }

        this.login.loading = true

        this.axios.post(`/api/v1/user/${this.login.username}/login`, {
          password: this.login.password
        }).then(res => {
          this.login.loading = false
          this.$store.commit('setUsername', res.data.username)
          this.$store.commit('setAdmin', res.data.admin)
          this.closeAccountModal()

          this.$socket.emit('accountEvent')
        }).catch(e => {
          this.login.loading = false
          this.ajaxErrorHandler(e, (error) => {
            let path = error.path

            if(this.signup.errors[path] !== undefined && this.signup.errors[path] !== undefined) {
              this.signup.errors[path] = error.message
            }
          })
        })
      }
    },
    created () {
      this.axios.get('/api/v1/kaverti/state')
              .then(res => {
                this.$store.commit('setSettings', res.data)
                this.$store.dispatch('setTitle', this.$store.state.meta.title)
              }).catch(err => {
        if(err.response.data.errors[0].name === 'noSettings') {
          this.$router.push('/start')
        } else {
          this.ajaxErrorHandler(err)
        }
      })

      this.axios.get('/api/v1/forums/category')
              .then(res => {
                this.$store.commit('addCategories', res.data)
                if(!this.$store.state.meta.title.length && this.$route.params.category) {
                  let selectedCategory = this.$route.params.category.toUpperCase()
                  let category = this.categories.find(c => c.value === selectedCategory)

                  this.$store.dispatch('setTitle', category.name)
                }
              })
              .catch(this.ajaxErrorHandler)
    },
    watch: {
      $route () {
        this.showMenu = false
      },
      '$store.state.ajaxErrorsModal': function(val) {
        if(val) {
          this.$refs.ajaxErrorsModalButton.focus()
        }
      }
    }
  }
</script>

<style lang="scss">
  // Import Main styles for this application
  @import 'assets/scss/style';
</style>
<style lang="css">
  @import 'https://kit-pro.fontawesome.com/releases/v5.14.0/css/pro.min.css';
</style>
