<i18n>
{
  "en": {
    "titleExisting": "Edit user",
    "titleNew": "Create user",
    "userCreated": "User was successfully created.",
    "userUpdated": "User was successfully updated."
  },
  "de": {
    "titleExisting": "Benutzer bearbeiten",
    "titleNew": "Benutzer erstellen",
    "userCreated": "Benutzer wurde erfolgreich erstellt.",
    "userUpdated": "Benutzer wurde erfolgreich aktualisiert."
  }
}
</i18n>

<template>
  <v-card>
    <v-card-title class="dialog-title elevation-3">
      <div class="headline">{{ dialog.info.id ? $t('titleExisting') : $t('titleNew') }}</div>
    </v-card-title>
    <v-card-text style="height: 100%;">
      <div class="edit-user">
        <signup v-model="userForm" ref="editComponent" :id="dialog.info.id"></signup>
      </div>
    </v-card-text>
    <v-divider></v-divider>
    <v-card-actions>
      <v-spacer></v-spacer>
      <v-btn flat="flat" @click="setDialog({ show: false })">{{ $t('cancel') }}</v-btn>
      <v-btn :color="dialog.info.id ? 'primary' : 'success'" @click="saveUser">{{ dialog.info.id ? $t('save') : $t('create') }}</v-btn>
    </v-card-actions>
  </v-card>
</template>

<script>
import { mapState, mapMutations, mapGetters } from 'vuex'
import signup from '@/components/UserCreateForm'

export default {
  name: 'UserModuleEdit',
  components: {
    signup
  },
  data () {
    return {
      userForm: { }
    }
  },
  computed: {
    ...mapState('users', ['dialog']),
    ...mapGetters(['user'])
  },
  methods: {
    ...mapMutations('setUserFullName', 'setUserName'),
    setDialog (data) {
      this.$store.commit('users/setDialog', data)
    },
    async saveUser () {
      if (this.$refs.editComponent.validate()) {
        var url = '/api/users'
        if (this.dialog.info.id) {
          url += '/' + this.dialog.info.id
        }
        this.$http.post(url, {
          username: this.userForm.username,
          password: this.userForm.password,
          name: this.userForm.name,
          email: this.userForm.email
        }).then(response => {
          if (this.dialog.info.id === this.user.id) this.$store.dispatch('loadUser')
          this.$store.dispatch('users/loadData')
          this.setDialog({ show: false })
          this.$snackbar({ color: 'success', text: this.dialog.info.id ? this.$t('userUpdated') : this.$t('userCreated') })
        }).catch(error => {
          if (error.response.data.error === 'USER_ALREADY_EXISTS') {
            this.$refs.editComponent.setUsernameTakenError()
          }
        })
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.dialog-title {
  z-index: 1;
}
.selected-list {
  padding: 30px;
}
.edit-user {
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>
