<template>
  <div class="dashboard">
    <h1>{{ $t('settings.profileSettings') }}</h1>

    <ul v-if="user.admin">
      <li><router-link to="/settings/global">{{ $t('settings.goTo') }} {{ $t('settings.globalSettings') }}</router-link></li>
    </ul>

    <form @submit="changePassword">
      <h2>{{ $t('settings.changePassword') }}</h2>
      <p><input :class="passwordClass" type="password" :placeholder="$t('settings.newPassword')" v-model="password" name="password"></p>
      <p><input :class="passwordClass" type="password" :placeholder="$t('settings.newPasswordConfirm')" v-model="passwordConf" name="password"></p>
      <p><input type="submit" :value="$t('buttons.update')"></p>
    </form>

    <form @submit="updateCSS">
      <h2>{{ $t('settings.changePassword') }}</h2>
      <textarea v-model="css" name="css"></textarea>
      <p><input type="submit" :value="$t('buttons.update')"></p>
    </form>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import api from '@/utils/api'

export default {
  name: 'settings',
  data: function () {
    return {
      password: '',
      passwordConf: '',
      css: ''
    }
  },
  computed: {
    ...mapState([ 'user' ]),
    passwordClass () {
      if (this.password === '' && this.passwordConf === '') {
        return ''
      }

      if (this.password === this.passwordConf) {
        return 'green'
      }

      return 'red'
    }
  },
  created () {
    this.css = this.user.css
  },
  methods: {
    ...mapMutations([ 'showSuccess' ]),
    changePassword (event) {
      event.preventDefault()

      if (this.password !== this.passwordConf) {
        return
      }

      api.updatePassword(this.password).then(() => {
        this.showSuccess('Password updated!')
      }).catch(e => {
        this.$store.commit('showError', e)
      })
    },
    updateCSS (event) {
      event.preventDefault()

      api.updateCSS(this.css).then(() => {
        this.$store.commit('setUserCSS', this.css)
        this.$emit('css-updated')
        this.showSuccess('Styles updated!')
      }).catch(e => {
        this.$store.commit('showError', e)
      })
    }
  }
}
</script>
