<i18n>
{
  "en": {
    "confirmPassword": "Confirm Password",
    "createRoot": "There are no users yet, create the root account.",
    "email": "E-Mail",
    "emailError": "E-mail must be valid.",
    "name": "Name",
    "password": "Password",
    "passwordEmptyError": "Password can not be empty.",
    "passwordLengthError": "Minimum 8 characters required.",
    "passwordMatchError": "Passwords do not match.",
    "rootCreated": "Root account successfully created.",
    "username": "Username",
    "usernameEmptyError": "Username can not be empty."
  },
  "de": {
    "confirmPassword": "Passwort bestätigen",
    "createRoot": "Es gibt noch keine Benutzer, erstelle den Root-Account.",
    "email": "E-Mail",
    "emailError": "Keine gültige E-Mail.",
    "name": "Name",
    "password": "Passwort",
    "passwordEmptyError": "Passwort kann nicht leer sein.",
    "passwordLengthError": "Es sind mindestens 8 Zeichen erforderlich.",
    "passwordMatchError": "Passwörter stimmen nicht überein.",
    "rootCreated": "Der Root Account wurde erfolgreich erstellt.",
    "username": "Benutzername",
    "usernameEmptyError": "Benutzername kann nicht leer sein."
  }
}
</i18n>

<template>
  <div class="setup-page">
    <label class="error--text" style="font-size: large; margin-bottom: 20px;margin-top: -20px;">{{ $t('createRoot') }}</label>
    <div class="text-right">
      <signup v-model="user" ref="setupRoot"></signup>
      <v-btn @click="setup" class="setup-button primary" raised>{{ $t('signup') }}</v-btn>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import signup from '@/components/UserCreateForm'

export default {
  name: 'StartPageSetup',
  components: {
    signup
  },
  data () {
    return {
      user: { }
    }
  },
  methods: {
    setup () {
      if (this.$refs.setupRoot.validate()) {
        this.$http.post('/api/setup', {
          username: this.user.username,
          password: this.user.password,
          name: this.user.name,
          email: this.user.email
        }).then(response => {
          this.$snackbar({ color: 'success', text: this.$t('rootCreated'), timeout: 15000 })
          this.$router.replace({ name: 'login' })
        }).catch(error => {
          this.$snackbar({ color: 'error', text: error.response.data.message, timeout: 15000 })
        })
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    // If there are already users in the db, redirect to the login page.
    Vue.prototype.$http.get('/api/setup/status').then(result => {
      console.log(result.status === 200)
      if (result.status === 200) {
        next()
      } else {
        next({ name: 'login' })
      }
    }).catch(() => {
      next({ name: 'login' })
    })
  }
}
</script>

<style scoped>
.setup-page {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.setup-button {
  margin-top: 20px;
}
</style>
