<template lang="pug">
  modal(:show='show', @close='close')
    .modal-header
      h3 Edit User
    .modal-body
      .alert.alert-danger(v-if='error') {{ error }}
      .form-group
        label(for="username") Username
        input.form-control(type="text" id="username" name="username" v-model="username")
      .form-group
        label(for="display_name") Display Name
        input.form-control(type="text" id="display_name" name="display_name" v-model="display_name")
      .form-group
        label(for="email") Email
        input.form-control(type="email" id="email" name="email" v-model="email")
      .form-group
        label(for="privilege") Privilege
        input(type="range" min="0" max="5" step="1" id="privilege" name="privilege" v-model="nw_privilege")
        span#priv-num {{ nw_privilege }}
      .form-check
        input.form-check-input(type="checkbox" id="activated" name="activated" v-model="activated")
        label.form-check-label(for="activated") Activated
    .modal-footer.text-right
      button.btn.btn-primary(@click='submit') Done
      button.btn.btn-secondary(@click='close') Cancel
</template>

<script type="text/javascript">
  import Modal from './Modal.vue'
  const csrfToken = document.querySelector('meta[name="csrf-token"]').content

  export default {
    props: ['show', 'id'],
    data: function () {
      return {
        error: '',
        username: '',
        display_name: '',
        email: '',
        nw_privilege: 0,
        activated: false
      }
    },
    components: {
      Modal
    },
    methods: {
      close: function () {
        this.$emit('close')
        this.error = ''
        this.username = ''
        this.display_name = ''
        this.email = ''
        this.nw_privilege = 0
        this.activated = true
      },
      submit: function () {
        this.$http.post('/admin/api/user', {
          user_id: this.id,
          username: this.username,
          display_name: this.display_name,
          email: this.email,
          nw_privilege: this.nw_privilege,
          activated: this.activated,
          csrf: csrfToken
        }).then(data => {
          this.close()
          this.$root.$emit('reload_users')
        }).catch(err => {
          console.error(err)
          if (err.body && err.body.error) this.error = err.body.error
        })
      }
    },
    watch: {
      id: function () {
        if (this.id <= 0) return
        this.$http.get('/admin/api/user/' + this.id).then(data => {
          let dr = data.body

          this.username = dr.username
          this.display_name = dr.display_name
          this.email = dr.email
          this.nw_privilege = dr.nw_privilege
          this.activated = dr.activated
        }).catch(err => {
          alert('Failed to fetch user information')
          this.close()
        })
      }
    }
  }
</script>
