<template>
  <q-page class="row q-pa-md q-gutter-md column">
    <q-card v-for="(book, index) in books" :key="index">
      <q-card-section>
        {{ book.title }} - {{ book.in_library }} - {{ book.lcc }}
        <q-btn label="Edit" color="primary" @click="books_dialog = true; active_book = book" size="large"/>
        <ul>
          <li v-for="(datapoint, index2) in book.data" :key="index2">
            {{ datapoint.created }} -
            {{ datapoint.pages }}
          </li>
        </ul>
      </q-card-section>
    </q-card>
    <q-dialog v-model="books_dialog" persistent width="50%">
      <q-card>
        <q-card-section>
          <q-form @submit.prevent="submit_book">
            <q-input label="Title" v-model="active_book.title"></q-input>
            <q-toggle label="In Library" v-model="active_book.in_library"></q-toggle>
            <q-input label="LCC" v-model="active_book.lcc"></q-input>
            <q-btn label="Submit" type="submit" color="primary" size="large"/>
          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script>
import { defineComponent, ref } from 'vue'
import {
  get_books,
  get_book_datapoint,
  edit_book,
} from '../api.js'

export default defineComponent({
  name: 'BookPage',
  setup(){
    let books = ref([])
    get_books().then(json => {
      books.value = json
      books.value.forEach(book => {
        book.data = []
      })
      get_book_datapoint().then(json => {
        json.forEach(datapoint => {
          let book = books.value.find(book => {
            return book.id == datapoint.book_id
          })
          book?.data.push(datapoint)
        })
      })
    })
    let books_dialog = ref(false)
    let active_book = ref(null)
    return {
      books: books,
      books_dialog,
      active_book,
      submit_book(){
        edit_book(active_book.value)
        books_dialog.value = false
      }
    }
  }
})
</script>
