<template>
  <v-container>
    <v-toolbar flat color="white">
      <v-text-field
        v-model="search"
        append-icon="mdi-magnify"
        label="Recherche"
        single-line
        hide-details
        @change="searchDoc"
      />
      <v-spacer />
      <v-btn color="primary" @click="createDoc()">
        <v-icon>mdi-plus</v-icon>
      </v-btn>
    </v-toolbar>

    <v-data-table
      :headers="headers"
      :items="docs"
      :loading="loading"
      :options.sync="options"
      :server-items-length="nbDocs"
      class="elevation-2"
    >
      <template v-slot:items="props">
        <td>{{ props.item.name }}</td>
        <td>
          <v-icon small class="mr-2" @click="editDoc(props.item)">
            edit
          </v-icon>
          <v-icon small @click="deleteDoc(props.item)">
            delete
          </v-icon>
        </td>
      </template>
      <template v-slot:item.action="{ item }">
        <v-icon
          small
          class="mr-2"
          @click="editDoc(item)"
        >
          mdi-pencil
        </v-icon>
        <v-icon
          small
          @click="deleteDoc(item)"
        >
          mdi-delete
        </v-icon>
      </template>
    </v-data-table>

    <v-dialog v-model="openCreateDialog" persistent max-width="600px">
      <v-card>
        <v-card-title>
          <span class="headline">Create new item</span>
        </v-card-title>
        <v-card-text>
          <v-container v-if="newItem.form" grid-list-md>
            <form-gen
              :value="newItem.doc"
              :form="newItem.form"
              :coll="{type: $route.params.rsc, id: null}"
              @valid="newItemIsValid"
            />

            <v-alert :value="newItem.hasError" type="error">
              {{ newItem.hasError }}
            </v-alert>
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn color="blue darken-1" text @click="openCreateDialog = false">
            Cancel
          </v-btn>
          <v-btn color="primary" text :disabled="!newItem.isValid" @click="newItemCreate">
            Create
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<script>
import FormGen from '@/components/FormGen/FormGen'
export default {
  layout: 'admin',
  components: { FormGen },
  data: () => ({
    docs: [],
    jsonForm: null,
    openCreateDialog: false,
    loading: false,
    nbDocs: 0,
    options: {},
    search: '',
    newItem: {
      doc: {},
      form: null,
      hasError: null,
      isValid: false
    },
    headers: [
      { text: 'Name', align: 'left', value: 'name' },
      { text: 'Actions', value: 'action', align: 'right', sortable: false }
    ]
  }),
  watch: {
    options: {
      handler () {
        this.getDataFromApi()
      },
      deep: true
    }
  },
  mounted () {
    this.$store.commit('admin/ui/setTitle', 'Resources')
    this.$store.commit('admin/ui/setBreadcrumbs', [
      { text: 'Admin', to: '/admin' },
      { text: 'Resources', to: '/admin/resources' },
      { text: this.$route.params.rsc, to: `/admin/resources/${this.$route.params.rsc}` }
    ])
    this.getListingHeader()
  },
  methods: {
    editDoc (item) {
      this.$router.push({ path: `/admin/resources/${this.$route.params.rsc}/${item._id}` })
    },
    deleteDoc (item) {},
    createDoc () {
      this.getCreateForm()
    },
    searchDoc () {
      this.getDataFromApi()
    },
    getCreateForm () {
      this.$axios.get(`/cloud/api/${this.$route.params.rsc}/private/json-form-create`)
        .then((res) => {
          this.newItem.doc = {}
          this.newItem.form = res.data
          this.openCreateDialog = true
        })
    },
    getListingHeader () {
      this.$axios.get(`/cloud/api/${this.$route.params.rsc}/private/listing-header`)
        .then((res) => {
          this.headers = res.data
          this.headers.push({ text: 'Actions', value: 'action', align: 'right', sortable: false })
        })
    },
    newItemIsValid (pVal) {
      this.newItem.isValid = pVal
    },
    newItemCreate () {
      this.newItem.hasError = null
      if (!this.newItem.isValid) { return }
      this.$axios.post(`/cloud/api/${this.$route.params.rsc}`, this.newItem.doc)
        .then((res) => {
          this.$router.push({ path: `/admin/resources/${this.$route.params.rsc}/${res.data.doc._id}` })
        })
        .catch((res) => {
          this.newItem.hasError = 'Impossible de créer le nouvel item'
        })
    },
    newItemCancel () {
      this.newItem.doc = {}
      this.newItem.form = null
      this.newItem.isValid = false
      this.openCreateDialog = true
    },
    getDataFromApi () {
      const { sortBy, sortDesc, page, itemsPerPage } = this.options
      this.loading = true
      const queries = []
      const sort = sortBy.length ? sortBy[0] : 'name'
      const desc = sortDesc.length ? sortDesc[0] : true
      const search = this.search

      queries.push(`limit=${itemsPerPage}`)
      queries.push(`skip=${itemsPerPage * (page - 1)}`)
      queries.push(`sort=${desc ? '' : '-'}${sort}`)
      if (search) {
        queries.push(`name__regex=${search},i`)
      }

      this.$axios.get(`/cloud/api/${this.$route.params.rsc}?${queries.join('&')}`)
        .then((res) => {
          this.$store.commit('admin/ui/setTitle', res.data.label)
          this.nbDocs = res.data.count
          this.docs = res.data.data
          this.loading = false
        })
    }
  }
}
</script>
