<template>
  <div class="q-pa-md">
    <form class="register" autocomplete="off">
      <div class="q-pa-md">
        <div class="column q-gutter-lg" style="">
          <div class="col">
            <div class="">
              <div class="" style="max-width: 440px">
                <q-input lazy-rules outlined filled stack-label v-model="user.name" type="text" label="Benutzername"
                         :rules="[val=>val.length>=2||'Name muss mindestens 2 Zeichen lang sein!']"/>
              </div>
            </div>
          </div>
          <div class="col">
            <div class="">
              <div class="" style="max-width: 440px">
                <q-input lazy-rules outlined filled stack-label v-model="user.email" type="text" label="E-Mail"
                         :rules="[val=>validateEmail(val)||'Bitte gültige E-Mail angeben!']"/>
              </div>
            </div>
          </div>
          <div class="col">
            <div class="">
              <div class="" style="max-width: 440px">
                <q-input lazy-rules outlined filled stack-label v-model="user.checkemail" type="text"
                         label="E-Mail erneut eingeben" placeholer="Email"
                         :rules="[val=>val===user.email||'E-Mail stimmt nicht überein!']"/>
              </div>
            </div>
          </div>
          <div class="col">
            <div class="">
              <div class="" style="max-width: 440px">
                <q-input lazy-rules outlined filled stack-label v-model="user.password" type="password"
                         label="Passwort"
                         :rules="[val=>val.length>=8||'Passwort muss mindestens 8 Zeichen lang sein!']"/>
              </div>
            </div>
          </div>
          <div class="col">
            <div class="">
              <div class="" style="max-width: 440px">
                <q-input lazy-rules outlined filled stack-label v-model="user.checkpassword" type="password"
                         label="Passwort erneut eingeben"
                         :rules="[val=>val===user.password||'Passwort stimmt nicht überein']"/>
              </div>
            </div>
          </div>
          <div class="col">
            <div class="">
              <div class="" style="max-width: 440px">
                <q-btn
                  :disabled="!validationSuccesful"
                  label="Registrieren"
                  color="primary"
                  class="full-width"
                  @click="register()"
                  unelevated
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </form>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        user: {
          name: "",
          email: "",
          checkemail: "",
          password: "",
          checkpassword: "",
        },
      }
    },
    computed: {
      validationSuccesful() {
        if (this.user.name.length >= 2
          && this.validateEmail(this.user.email)
          && this.user.email === this.user.checkemail
          && this.user.password.length >= 8
          && this.user.password === this.user.checkpassword) {
          return true;
        }
        return false;
      }
    },
    created() {
      this.login();
    },
    methods: {
      validateEmail(email) {
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(String(email).toLowerCase());
      },
      register: function () {

        if (this.user.email === this.user.checkemail && this.user.password === this.user.checkpassword) {
          const data = {
            name: this.user.name,
            password: this.user.password,
            email: this.user.email,
            roles: [
              {
                role: "CACHER",
                domain: "geocaching.de"
              }
            ]
          };

          console.log("POST /api/register/ - json: " + JSON.stringify(data));
          const token = JSON.parse(localStorage.getItem('registerToken')).token;
          this.$axios.post(process.env.USER_API + '/account/register', data, {
            headers: {
              'Authorization': 'Bearer ' + token,
            }
          })
            .then((response) => {
              console.log(response.data);
              if (response.status === 201) {
                this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {
                  message: "Deine Registrierung war erfolgreich!",
                  title: "Registrierungsprozess",
                  color: "blue"
                });
                this.autoLogin();
              }
            })
            .catch((error) => {
              let message;
              let header = "Unbekannter Fehler...";
              if (error.response) {
                console.log(error.response)
                if (error.response.status === 409) {
                  message= "Die E-Mail-Adresse wird bereits verwendet!";
                  header= "Anmeldedaten überprüfen!";
                }
              } else if (error.request) {
                console.log(error.request);
                header = "Anfrage fehlgeschlagen!";
                message = "Die Verbindung zum Server ist gestört. Versuchen Sie es später noch einmal.";
              }
              this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {message: message, title: header});
            });
        } else {

          if (this.user.email != this.user.checkemail) {
            this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {
              message: "Email stimmt nicht überein",
              title: "Fehler",
            });
          } else if (this.user.password != this.user.checkpassword) {
            this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {
              message: "Passwort stimmt nicht überein",
              title: "Fehler",
            });
          }
        }
      },
      login() {
        console.log("MasterUser()")
        const logindata = {
          email: "register@bugageocaching.de",
          password: "reguser2019"
        };
        this.$axios.post(process.env.USER_API + '/account/login', logindata)
          .then((response) => {
            localStorage.setItem('registerToken', JSON.stringify(response.data));
          });
      },
      autoLogin() {
        console.log("autoLogin()");
        const data = {
          email: this.user.email,
          password: this.user.password,
        };
        console.log(data);
        this.$axios.post(process.env.USER_API + '/account/login', data)
          .then((response) => {
            localStorage.setItem('userToken', JSON.stringify(response.data));
            localStorage.setItem('userMail', JSON.stringify(data.email));
            this.$store.commit('auth/SET_AUTHENTICATED');
            this.$store.commit('auth/SET_USER');
            this.$router.push({path: `/overview`});
          })
          .catch((error) => {
            this.$router.push("/login");
          })
          .finally(() => {
          });

      },
    },
  };
</script>
