<template>
  <section class="section-container">
    <v-row class="signin">
      <v-spacer />
      <v-col cols="10" sm="8" md="6" lg="4" class="text-center">
        <h2 class="grey--text lighten-4">Register</h2>
        <UserAuthForm
          :submitFunc="register"
          successMessage
          errorMessage
          success
          error
          buttonText="Register"
        />
        <v-container class="pt-50">
        <v-alert
          v-model="success"
          prominent
          dense
          type="success"
          transition="slide-y-transition"
        >
          {{ successMessage }}
        </v-alert>
        <v-alert
          v-model="error"
          prominent
          dense
          type="error"
          transition="slide-y-transition"
        >
          {{ errorMessage }}
        </v-alert>
        </v-container>
      </v-col>
      <v-spacer />
    </v-row>
    
  </section>
</template>

<script>
import UserAuthForm from "@/components/UserAuthForm.vue"
import axios from 'axios'

export default {
  name: "Register",
  components: {
    UserAuthForm,
  },
  data: () => ({
    successMessage: null,
    errorMessage: null,
    success: false,
    error: false,
  }),
  methods: {
    async register(payload) {
      axios
        .post("http://localhost:8000/api/users/register", payload)
        .then((response) => {
          if (response.status == 200) {
            axios
              .post("http://localhost:8000/api/users/login", payload)
              .then((response) => {
                if (response.status == 200) {
                  this.successMessage = "Registration Successful";
                  this.success = true;
                  setTimeout(() => {
                    this.$router.push({ name: "Dashboard" });
                  }, 2000);
                }
              })
              .catch((error) => {
                this.errorMessage = error.response.data.error;
                this.error = true;
                setTimeout(() => {
                  this.errorMessage = null;
                  this.error = false;
                }, 3000);
              });
          }
        })
        .catch((error) => {
          console.log(error)
          this.errorMessage = error.response.data.error;
          this.error = true;
          setTimeout(() => {
            this.errorMessage = null;
            this.error = false;
          }, 3000);
        });
    },
    clear() {
      // you can use this method to clear login form
      this.username = "";
      this.password = null;
    },
  },
};
</script>
