<template>
  <div class="password-reset">
    <h2 class="password-reset__header">Passwort ändern</h2>
    <div v-if="showSuccess" class="success-message">
      <p class="success-message__msg" data-cy="password-change-success">Dein Password wurde erfolgreich geändert.</p>
    </div>
    <password-change-form
      @passwordSubmited="resetPassword"
      :oldPasswordErrors="oldPasswordErrors"
      :newPasswordErrors="newPasswordErrors" />
  </div>
</template>

<script>

  import UPDATE_PASSWORD_MUTATION from '@/graphql/gql/mutations/updatePassword.gql';
  import PasswordChangeForm from '@/components/profile/PasswordChangeForm'

  export default {
    components: {
      PasswordChangeForm
    },

    data() {
      return {
        oldPasswordErrors: [],
        newPasswordErrors: [],
        showSuccess: false
      }
    },
    methods: {
      resetPassword (passwords) {
        this.$apollo.mutate({
          mutation: UPDATE_PASSWORD_MUTATION,
          variables: {
            input: {
              passwordInput: passwords
            }
          }
        }).then(({ data }) => {
          if (data.updatePassword.success) {
            this.oldPasswordErrors = [];
            this.newPasswordErrors = [];
            this.showSuccess = true;
            this.$root.$emit('reset-password-form')
          } else {
            // currently we just have one error per field
            const error = data.updatePassword.errors[0]
            if (error.field === 'old_password') {
              this.handleOldPasswordError(error);
            } else {
              this.handleNewPasswordError(error)
            }
          }
        }).catch((error) => {
          console.log('fail', error)
        });
      },
      handleOldPasswordError (error) {
        this.oldPasswordErrors = error.errors.map((fieldError) => {
          if (fieldError.code === 'invalid') {
            return 'Die Eingabe ist falsch'
          }
        });
      },
      handleNewPasswordError (error) {
        this.newPasswordErrors = error.errors.map((fieldError) => {
          if (fieldError.code === 'invalid') {
            return 'Das Passwort muss Grossbuchstaben, Zahlen und Sonderzeichen beinhalten'
          } else if (fieldError.code === 'min_length') {
            return 'Das Passwort muss mindestens 8 Zeichen lang sein.'
          }
        });
      }
    }
  }
</script>

<style scoped lang="scss">
  @import "@/styles/_variables.scss";

  .success-message {
    margin-bottom: 20px;

    &__msg {
      color: $color-accent-4-dark;
      font-family: $sans-serif-font-family;
    }
  }

</style>
