<template>
  <div id="login-form" class="column-container">
    <form v-on:submit.prevent="login" class="column-container">
      <label for="username">Username</label>
      <input id="username" type="text" v-model="formInput.username"
             maxlength="50" autocomplete="off" required>
      <br>

      <label for="password">Password</label>
      <input id="password" type="password" v-model="formInput.password"
             minlength="5" required>
      <br>

      <Button type="submit">{{ this.buttonValue }}</Button>
    </form>
  </div>

</template>

<script>
import { postJson } from '@/util/fetch';
import Button from "@/components/Button";

export default {
  components: { Button },
  props: {
    path: String,
    buttonValue: String
  },
  data() {
    return {
      formInput: {
        username: undefined,
        password: undefined,
      }
    }
  },
  methods: {
    login() {
      const body = {
        username: this.formInput.username,
        password: this.formInput.password,
      };

      postJson(this.path, body).then(async response => {
        const data = await response.json();

        if (response.ok) {
          this.$emit('success', data);
        } else {
          this.$emit('error', data);
        }
      });
    }
  }
}
</script>
