<template>

    <v-app>
      <top-bar :show-back-icon="true" :page-title="pageTitle" />  
      <v-main>
        <v-container>
          <v-form name="register-form">
            <div class="mb-3">
              <label for="username">Username: </label>
              <input type="text" id="username" v-model="input.username" />
            </div>
            <div class="mb-3">
              <label for="password">Password: </label>
              <input type="password" id="password" v-model="input.password" />
            </div>
            <div class="mb-3">
              <label for="password">Password Confirmation: </label>
              <input type="password" id="passwordConfirm" v-model="input.passwordConfirm" />
            </div>
            
          </v-form>
        </v-container>
        
              <v-btn @click.prevent="register">สมัครสมาชิค</v-btn>
         
      </v-main>
    </v-app>
  
  </template>
  
  <script>
  import TopBar from '@/components/TopBar.vue';
  
  export default {
    components: {
      TopBar
    },
    name: 'register',
    data() {
      return {
        pageTitle: 'สมัครสมาชิค', 
        input: {
          username: '',
          password: '',
          passwordConfirm:''
        }
      };
    },
    methods: {
      register() {
        if (this.input.username !== '' && ((this.input.password !='') && (this.input.password == this.input.passwordConfirm))) {
          console.log('Authenticated: Checking with Backend');
          fetch("http://localhost:5000/api/users/create", {
            method: "POST",
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              username: this.input.username,
              password: this.input.password,
              email: "asdf",
              isGoogleAccount: false
            })
            })
            .then((res) => {
              if(res.ok){
                return res.json()
              }
              else{
                return res.json().then(data => {throw Error(`${data.registerStatus}`) });
              }
            })
            .then((data) => {
              console.log(data.registerStatus)
              this.$router.push({name : 'login'})
            })
            .catch((err) =>{
              console.log(err)
            })
            console.log("fisnished fetch");
        } else {
          console.log('Username and Password cannot be empty');
        }
      }
    }
  };
  </script>
  