<template>
  <main>
    <div class="container-fluid c-section">
      <div class="row">
        <div class="col-sm-3"></div>
        <div class="col-sm-6">
          <div class="a-spacing-top-medium"></div>
          <h2>Add a new Owner</h2>
          <form action="">
            <!-- name -->
            <div class="a-spacing-top-medium">
              <label for="">Name</label>
              <input v-model="name" type="text" class="a-input-text" />
            </div>

            <!-- About -->
            <div class="a-spacing-top-medium">
              <label for="">About</label>
              <input v-model="about" type="text" class="a-input-text" />
            </div>

            <!-- Photo input-->
            <div class="a-spacing-top-medium">
              <label for="" style="margin-bottom: 0px;">Photo</label>
              <div class="a-row a-spacing-top-medium">
                <label class="choosefile-button">
                  <i class="fa fa-plus"></i>
                  <input @change="onFileSelected" type="file" />
                  <p style="margin-top: -70px">{{ fileName }}</p>
                </label>
              </div>
            </div>


            <hr/>
            <!--Button-->
            <div class="a-spacing-top-large">
              <span class="a-button-register">
                <span @click="onAddOwner" class="a-button-text">Add Owner</span>
              </span>
            </div>
          </form>
          <br/>
          <ul class="list-group-item">
            <li v-for="owner in owners" :key="owner._id">{{ owner.name }}</li>
          </ul>
        </div>
        <div class="col-sm-3"></div>
      </div>
    </div>
  </main>
</template>

<script>
export default {
  async asyncData ({ $axios }) {
    try {
      let response = await $axios.$get('http://localhost:3000/api/owners')
      console.log(response)
      return {
        owners: response.owners
      }
    } catch (err) {
      console.log(err)
    }
  },
  data () {
    return {
      name: '',
      about: '',
      selectedFile: null,
      fileName: ''
    }
  },
  methods: {
    onFileSelected (event) {
      this.selectedFile = event.target.files[0]
      console.log(this.selectedFile)
      this.fileName = event.target.files[0].name
    },

    async onAddOwner () {
      try {
        let data = new FormData()

        data.append('name', this.name)
        data.append('about', this.about)
        data.append('photo', this.selectedFile, this.selectedFile.name)

        let result = await this.$axios.$post('http://localhost:3000/api/owners', data)
        this.owners.push({ name: this.name })
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>
