<style>
  h1 {
    font-size: 32px ;
  }
  h2 {
    font-size: 24px ;
  }
</style>
<template>
	<div class='route_container'>
		<confirm-modal
			v-model='showConfirmModal'
			@confirm='deleteAccount'
			color='is-danger'
			text='Send email'
		>
      <div class="card-content">
        When submitting this, you will receive an email sent to your email address to proceed with account deletion.
      </div>
		</confirm-modal>
    <modal-window v-model='showLoginModal' style='z-index: 100' width='25rem' :no-padding='true' :is-error="true">
      <div slot="header">
        You have been logged out.
      </div>
      <div slot='main'>
        <p style='margin: 1rem;'>You have been logged out, please login with your new username, or email.</p>
      </div>
      <button
        slot='footer'
        class='button is-info'
        style='z-index: 100; width: 100%;'
        @click='showLoginModal = false'
        ref='ajaxErrorsModalButton'
      >
        Okay
      </button>
    </modal-window>
    <modal-window v-model='emailCheckDelete' style='z-index: 100' width='25rem' :no-padding='true' :is-error="true">
      <div slot="header">
        You've got mail
      </div>
      <div slot='main'>
        <p style='margin: 1rem;'>An email has been sent to delete your account, and to confirm that you're the true owner of the account.</p>
      </div>
      <button
        slot='footer'
        class='button is-info'
        style='z-index: 100; width: 100%;'
        @click='emailCheckDelete = false'
        ref='ajaxErrorsModalButton'
      >
        Okay
      </button>
    </modal-window>

		<h1>Account settings</h1>
    <br>
		<div>
			<h2>Change your password</h2>
			<p class='p--condensed'>
				For security, enter your current password
			</p>
			<div>
				<fancy-input
					placeholder='Current password'
					v-model='password.current'
					:error='password.errors["current password"]'
					type='password'
				></fancy-input>
			</div>
			<div>
				<fancy-input
					placeholder='New password'
					v-model='password.new'
					:error='password.errors["new password"]'
					type='password'
				></fancy-input>
			</div>
			<b-button
				class='button is-success'
				@click='savePassword'
				:loading='password.loading'
			>Change password</b-button>
		</div>
    <div>
      <h2>Change your username</h2>
      <b>
        Changing your username will cost 200 Koins!
      </b>
      <div>
        <fancy-input
          placeholder='Current password'
          v-model='username.password'
          :error='username.errors["password"]'
          type='password'
        ></fancy-input>
      </div>
      <div>
        <fancy-input
          placeholder='New username'
          v-model='username.username'
          :error='username.errors["username"]'
        ></fancy-input>
      </div>
      <b-button
        class='button is-success'
        @click='saveUsername'
        :loading='username.loading'
      >Change username</b-button>
    </div>
    <div>
      <br>
      <h2>Change your email address</h2>
      <p>Your email is currently: {{$store.state.email}}</p>
      <p v-if="$store.state.emailVerified">Your email is verified!</p>
      <p v-if="!$store.state.emailVerified">Your email is not verified, you may lose some functionality in the future with an unverified email address, if you entered your email wrong, you can change it here, or resend it.</p>
      <b-button @click='verifyEmailResend' :loading='email.loading' v-if="!$store.state.emailVerified">Resend Verification Email</b-button>
      <p v-if="$store.state.emailVerified == null">Connecting...</p>
      <p v-if="$store.state.emailVerified == undefined">Connecting...</p>
      <div>
      <fancy-input
        placeholder='New email'
        v-model='email.new'
        :error='email.errors["new email"]'
        type='email'
      ></fancy-input>
    </div>
      <div>
        <fancy-input
          placeholder='Current password'
          v-model='email.currentPassword'
          :error='email.errors["email current password"]'
          type='password'
        ></fancy-input>
      </div>
    <b-button
      class='button is-success'
      @click='saveEmail'
      :loading='email.loadingChange'
    >Change email address</b-button>
    </div>
    <div>
      <br>
      <h2>Enable 2 Factor Authentication <trpl-para>(Highly Recommended)</trpl-para></h2>
      <p class='p--condensed'>
        For security, enter your current password
      </p>
      <b-button
        class='button is-success'
        @click='save2FA'
        :loading='totp.loading'
      >Enable 2FA</b-button>
    </div>
		<div>
      <br>
			<h2>Dangerous Options!</h2>
      <h3>Kill all sessions</h3>
      <p>
        You'll be immediately logged out, along with all active sessions, this is useful if you think someone else is using your account, changing your password will also invalidate all sessions.
      </p>
      <b-button
        class='button is-danger'
        :loading='invalidateSessionLoading'
        @click='invalidateSession()'
      >Invalidate sessions</b-button>
      <h3>Delete your account</h3>
			<p>
				Once this is done, your account <strong>cannot</strong> be restored <br/>
				Your current posts however will be retained, and will show up as the [deleted] user.
			</p>
			<b-button
				class='button is-danger'
				:loading='deleteAccountLoading'
				@click='showConfirmModal = true'
			>Delete my account</b-button>
		</div>
	</div>
</template>

<script>
	import FancyInput from '../FancyInput'
  import ModalWindow from '../ModalWindow'
  import ConfirmModal from '../ConfirmModal'

	import AjaxErrorHandler from '../../assets/js/errorHandler'
	import logger from '../../assets/js/logger'
  import axios from "axios";

	export default {
		name: 'settingsAccount',
		components: {
			FancyInput,
			ConfirmModal,
      ModalWindow
		},
		data () {
			return {
				password: {
					loading: false,

					current: '',
					new: '',

					errors: {
						'new password': '',
            'current password': ''
					}
				},
        email: {
          loading: false,
          loadingChange: false,

          currentPassword: '',
          new: '',

          errors: {
            'new password': '',
            'email current password': ''
          }
        },
        username: {username: '',
          password: '',
          errors: {
            'username': '',
            'password': '',
          },
          loading: false,
        },
        deleteAcc: {
          loading: false,

          password: '',

          errors: {
            'current password': ''
          }
        },
        totp: {loading: false
        },

				deleteAccountLoading: false,
        invalidateSessionLoading: false,
        emailCheckDelete: false,
				showConfirmModal: false,
        showLoginModal: false
			}
		},
		computed: {},
		methods: {
      savePassword() {
        this.password.errors['current password'] = ''
        this.password.errors['new password'] = ''

        if (!this.password.current.length) {
          this.password.errors['current password'] = 'Cannot be blank'
          return
        }
        if (!this.password.new.length) {
          this.password.errors['new password'] = 'Cannot be blank'
          return
        }

        this.password.loading = true

        this.axios
          .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'user/' + this.$store.state.username, {
            currentPassword: this.password.current,
            newPassword: this.password.new
          })
          .then(() => {
            this.password.loading = false
            this.email.loading = false

            this.password.current = ''
            this.password.new = ''
          })
          .catch(e => {
            this.password.loading = false
            this.email.loading = false

            console.log(e)

            AjaxErrorHandler(this.$store)(e, error => {
              if (error.path === 'hash') {
                this.password.errors['new password'] = error.message
              }
            })
          })
      },
      saveEmail() {
        this.email.errors['email current password'] = ''
        this.email.errors['new email'] = ''

        if (!this.email.currentPassword.length) {
          this.email.errors['email current password'] = 'Cannot be blank'
          return
        }
        if (!this.email.new.length) {
          this.email.errors['new email'] = 'Cannot be blank'
          return
        }

        this.email.loadingChange = true

        this.axios
          .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'user/' + this.$store.state.username, {
            emailCurrentPassword: this.email.currentPassword,
            newEmail: this.email.new
          })
          .then(() => {
            this.email.currentPassword = ''
            this.email.newEmail = ''
            this.axios
              .post(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'users/email-verify/send')
              .then(() => {
                this.email.loadingChange = false
                AjaxErrorHandler("Success, your email has been changed, and a verification email has been sent to your new email: " + this.$store.state.email)
              })
              .catch(e => {
                this.email.loadingChange = false
                AjaxErrorHandler(this.$store)(e)
              })
            this.axios.get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'userinfo')
              .then(res => {
                this.$store.commit('setUsername', res.data.username)
                this.$store.commit('setEmail', res.data.email)
                this.$store.commit('setEmailVerified', res.data.emailVerified)
                this.$store.commit('setAdmin', res.data.admin)
              })
          })
          .catch(e => {
            this.email.loadingChange = false

            console.log(e)
            AjaxErrorHandler(this.$store)(e)
          })
          .catch(e => {
            this.showConn(e)
          })
      },

      save2FA() {
        this.totp.loading = true
        this.axios
          .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'users/preferences', {
            twoFactorGetCode: true
          })
          .then(() => {
            this.totp.loading = false
          })
          .catch(e => {
            this.totp.loading = false
            AjaxErrorHandler(this.$store)(e)
          })
      },
      invalidateSession() {
        this.invalidateSessionLoading = true
        this.axios
          .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'users/preferences', {
            invalidateSession: true
          })
          .then(() => {
            this.invalidateSessionLoading = false
          })
          .catch(e => {
            this.invalidateSessionLoading = false
            AjaxErrorHandler(this.$store)(e)
          })
      },
      saveUsername() {
        this.username.errors['username'] = ''

        if (!this.username.username.length) {
          this.username.errors['username'] = 'Cannot be blank'
          return
        }

        this.username.loading = true

        this.axios
          .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'users/preferences', {
            username: this.username.username,
            password: this.username.password,
            changeUsername: true
          })
          .then(() => {
            this.username.username = ''
            this.username.loading = false
            localStorage.removeItem('accessToken');
            this.$store.commit('setSessionToken', '')
            Object.assign(axios.defaults, {headers: {Authorization: this.$store.state.sessToken}})
            this.axios.get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'userinfo')
              .then(res => {
                this.$store.commit('setUsername', res.data.username)
                this.$store.commit('setEmail', res.data.email)
                this.$store.commit('setEmailVerified', res.data.emailVerified)
                this.$store.commit('setAdmin', res.data.admin)
                this.$store.commit('setKoins', res.data.koins)
                this.$store.commit('setDevMode', res.data.developerMode)
                this.$store.commit('setTheme', res.data.theme)
                this.$store.commit('setExecutive', res.data.executive)
                this.$store.commit('setUserId', res.data.id)
                this.axios.get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'kaverti/state')
                  .then(res => {
                    this.$store.commit('setSettings', res.data)
                    this.$store.dispatch('setTitle', this.$store.state.meta.title)
                    this.$store.commit('setAPIVersion', res.data.latestAPIVersion)
                    this.$store.commit('setLatestVersion', res.data.latestStableVersion)
                    this.closeConn()
                  }).catch(err => {
                  if(err.response.data.errors[0].name === 'noSettings') {
                    this.showConn()
                  } else {
                    this.showConn()
                  }
                })
              })
            this.showLoginModal = true
          })
          .catch(e => {
            this.username.loading = false

            AjaxErrorHandler(this.$store)(e)
          })
          .catch(e => {
            this.showConn(e)
          })
      },

      deleteAccount() {
        this.deleteAccountLoading = true
        this.axios
          .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'users/delete')
          .then(() => {
            this.deleteAccountLoading = false
            this.emailCheckDelete = true
          })
          .catch(e => {
            this.deleteAccountLoading = false
            console.log(e)
            AjaxErrorHandler(this.$store)(e)
          })
      },
      verifyEmailResend() {
        this.email.loading = true

        this.axios
          .post(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'users/email-verify/send')
          .then(() => {
            this.email.loading = false
          })
          .catch(e => {
            this.email.loading = false
            AjaxErrorHandler(this.$store)(e)
          })
      }
    },
		mounted () {
			this.$store.dispatch('setTitle', 'Account Settings')
      this.axios.get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'userinfo')
        .then(res => {
          this.$store.commit('setUsername', res.data.username)
          this.$store.commit('setEmail', res.data.email)
          this.$store.commit('setEmailVerified', res.data.emailVerified)
          this.$store.commit('setAdmin', res.data.admin)
        })
        .catch(e => {
          this.showConn(e)
        })
			logger('settingsAccount')
		}
	}
</script>

<style lang='scss' scoped>
	@import '../../assets/scss/variables.scss';

	@media (max-width: $breakpoint--tablet) {
		.h1 {
			display: none;
		}
	}
</style>
