<template>

  <q-dialog
    v-model="dialogModel"
    @before-hide="triggerDialogClose"
    :persistent="deleteOngoing"
    >
    <q-card
      v-if="!deleteOngoing"
      class="deleteDialog"
      dark
    >
      <q-card-section class="row justify-center text-center">
        <h6 class="text-center q-my-sm">Mass delete documents</h6>
      </q-card-section>

         <q-card-section class="row justify-center q-mx-xl">
          <div>
            The documents will be deleted <span class="text-bold text-secondary">FOREVER</span> with no way to retrieve them.
            <br>
            <span class="text-caption">(unless a previous save of the project exists from earlier time that cointains it)</span>
          </div>
        </q-card-section>

      <q-card-section>
        <div class="row justify-center">

          <q-select
            ref="ref_deleteDocument"
            class="deleteDocumentSelect"
            dark
            popup-content-class="menuResizer"
            menu-anchor="bottom middle"
            menu-self="top middle"
            :options="filteredExistingInput"
            use-input
            multiple
            use-chips
            filled
            label="Selected documents"
            input-debounce="500"
            v-model="deleteDocumentsModel"
            @filter="filterExistingSelect"
          >
            <template v-slot:append v-if="!hideAdvSearchCheatsheetButton">
              <q-btn round dense flat icon="mdi-help-rhombus" @click.stop.prevent="SSET_setAdvSearchWindowVisible"
              >
                <q-tooltip :delay="500">
                  Open search cheatsheet
                </q-tooltip>
              </q-btn>
            </template>
            <template v-slot:option="{ itemProps, itemEvents, opt }">
                <q-item
                  :class="{'hasTextShadow': textShadow, 'isMinor':opt.isMinor}"
                  v-bind="itemProps"
                  v-on="itemEvents"
                  :key="opt.id"
                  :style="`color: ${opt.color}; background-color: ${opt.bgColor}`"
                  @mouseleave="setDocumentPreviewClose"
                >
                <documentPreview
                  :document-id="opt._id"
                  :external-close-trigger="documentPreviewClose"
                  :special-z-index="999999999"
                  :custom-anchor="'top end'"
                  :custom-self="'center left'"
                  :custom-delay="1200"
                />
                  <q-item-section avatar>
                    <q-icon
                      :style="`color: ${retrieveIconColor(opt)}`"
                      :name="(opt.isCategory) ? 'fas fa-folder-open' : opt.icon"
                      />
                  </q-item-section>
                  <q-item-section>
                    <q-item-label>
                      <span class="isDeadIndicator" v-if="opt.isDead">
                        †
                      </span>
                      <span :class="{'isDead': (opt.isDead && !hideDeadCrossThrough)}" v-html="opt.label">
                      </span>
                    </q-item-label>
                    <q-item-label caption class="text-cultured" v-html="opt.hierarchicalPath"></q-item-label>
                    <q-item-label caption class="text-cultured" v-if="opt.tags">
                      <q-chip
                      v-for="(input,index) in opt.tags" :key="index"
                      outline
                      style="opacity: 0.8;"
                      size="12px"
                      class="text-cultured"
                      v-html="`${input}`"
                      >
                      </q-chip>
                    </q-item-label>
                  </q-item-section>
                </q-item>
            </template>
            <template v-slot:selected-item="scope">
              <q-chip
                removable
                dense
                @remove="removeInput(scope)"
                :tabindex="scope.tabindex"
                :color="(scope.opt.isAutoGenerated) ? 'teal-3' : 'accent'"
                text-color="dark"
                class="text-bold"
              >

                <div
                  class="relationShipChipOverlay"
                  @mouseleave="setDocumentPreviewClose"
                />

                <div class="relationShipChipContent">
                  <template v-if="scope.opt.isDead">
                    †
                  </template>
                  {{ stripTags(scope.opt.label) }}
                </div>
                <documentPreview
                  :special-z-index="999999999"
                  :custom-delay="1200"
                  :document-id="scope.opt._id"
                  :external-close-trigger="documentPreviewClose"
                />

              </q-chip>
            </template>
          </q-select>

        </div>

      </q-card-section>

      <q-card-actions align="right" class="q-mb-lg q-mr-sm">
        <q-btn flat label="Cancel" color="accent" v-close-popup class="q-mr-lg" />
          <q-btn
          :outline="deleteDocumentsModel.length !== 0"
          :flat="deleteDocumentsModel.length === 0"
          label="Delete selected documents"
          color="secondary"
          :disable="deleteDocumentsModel.length === 0"
          @click="deleteDocuments"
          />
      </q-card-actions>
    </q-card>

    <q-card v-if="deleteOngoing" dark class="deleteDialog">
        <q-card-section class="row justify-center">
        <h6 class="text-center q-my-sm">Deleting...</h6>
      </q-card-section>

      <q-card-section class="row justify-center q-mx-xl">
        <div>
          Current document: {{currentDocName}}
        </div>
      </q-card-section>

      <q-card-section class="row justify-center q-mx-xl q-mb-lg">
          <q-linear-progress stripe round dark size="20px" :value="progressCounter" color="primary" class="q-mt-sm">
            <div class="absolute-full flex flex-center">
              <q-badge text-color="accent" color="dark" :label="`${deletedDocuments}/${deleteDocumentsModel.length}`" />
            </div>
          </q-linear-progress>
      </q-card-section>
    </q-card>
  </q-dialog>

</template>

<script lang="ts">

import PouchDB from "pouchdb"

import { Component, Watch, Prop } from "vue-property-decorator"
import DialogBase from "src/components/dialogs/_DialogBase"
import { uid, extend } from "quasar"
import documentPreview from "src/components/DocumentPreview.vue"

import { I_ShortenedDocument } from "src/interfaces/I_OpenedDocument"
import { I_Blueprint } from "src/interfaces/I_Blueprint"
import { advancedDocumentFilter } from "src/scripts/utilities/advancedDocumentFilter"

import RobotoRegular from "src/assets/fonts/Roboto-Regular.ttf"
import RobotoBold from "src/assets/fonts/Roboto-Bold.ttf"
import ArialFallback from "src/assets/fonts/ArialUnicodeMS.ttf"

@Component({
  components: {
    documentPreview
  }
})

export default class DeleteProject extends DialogBase {
  RobotoRegular = RobotoRegular
  RobotoBold = RobotoBold
  ArialFallback = ArialFallback

  /**
   * React to dialog opening request
   */
  @Watch("dialogTrigger")
  openDialog (val: string|false) {
    if (val) {
      if (this.SGET_getDialogsState) {
        return
      }
      this.SSET_setDialogState(true)
      this.dialogModel = true

      this.resetLocalData()
      this.reloadOptions()
      this.populateDeleteObjectDialog()

      if (this.prepickedIds.length > 0) {
        // @ts-ignore
        this.deleteDocumentsModel = this.SGET_allDocuments.docs.filter(doc => {
          return this.prepickedIds.includes(doc._id)
        })
      }
    }
  }

  resetLocalData () {
    this.deleteDocumentsModel = []
  }

  @Prop(({
    default () {
      return []
    }
  })) readonly prepickedIds!: string[]

  setDocumentPreviewClose () {
    this.documentPreviewClose = uid()
  }

  /**
   * Reloads local options
   */
  reloadOptions () {
    this.textShadow = this.SGET_options.textShadow
    this.hideDeadCrossThrough = this.SGET_options.hideDeadCrossThrough
    this.hideAdvSearchCheatsheetButton = this.SGET_options.hideAdvSearchCheatsheetButton
  }

  /**
   * Hides the advanced search cheatsheet help button in relationship type fields.
   */
  hideAdvSearchCheatsheetButton = false

  /**
   * Determines if the "dead" document type should have a cross-text decoration or not
   */
  hideDeadCrossThrough = false

  /**
   * Determines if text shadow will be shows for accesiblity reasons or not
   */
  textShadow = false

  documentPreviewClose = ""

  /**
   * Currently being opened document
   */
  deleteDocumentsModel = [] as I_ShortenedDocument[]

  /**
   * Pre-filtered list based on the category inclussion or exlcussion
   */
  existingObjectsFullList = [] as I_ShortenedDocument[]

  /**
   * All currently loaded blueprints
   */
  allDocumentBluePrints = [] as I_Blueprint[]

  /**
   * Filtered list of items
   */
  filteredExistingInput = null as unknown as I_ShortenedDocument[]

  /**
   * Local list copty for filtering in order to not mess up the original list
   */
  listCopy: I_ShortenedDocument[] = []

  /**
   * Refocuses the first value in the selct upon filtering for intuitive keyboard control
   */
  async refocusSelect () {
    await this.$nextTick()
    /*eslint-disable */
    // @ts-ignore 
    this.$refs.ref_deleteDocument.setOptionIndex(-1)
    // @ts-ignore 
    this.$refs.ref_deleteDocument.moveOptionSelection(1, true) 
    /* eslint-enable */
  }

  /**
   * Filter the pre-filtered list
   */
  filterExistingSelect (val: string, update: (e: () => void) => void) {
    if (val === "") {
      update(() => {
        this.filteredExistingInput = this.existingObjectsFullList.filter((obj) => !obj.isMinor)
        if (this.$refs.ref_existingDocument && this.filteredExistingInput.length > 0) {
          this.refocusSelect().catch(e => console.log(e))
        }
      })
      return
    }

    update(() => {
      const needle = val.toLowerCase()
      this.listCopy = extend(true, [], this.existingObjectsFullList)
      this.filteredExistingInput = advancedDocumentFilter(needle, this.listCopy, this.allDocumentBluePrints, this.existingObjectsFullList)

      if (this.$refs.ref_existingDocument && this.filteredExistingInput.length > 0) {
        this.refocusSelect().catch(e => console.log(e))
      }
    })
  }

  /**
   * Set up up all data in to the dialog on popup load
   */
  populateDeleteObjectDialog () {
    this.allDocumentBluePrints = this.SGET_allBlueprints

    this.existingObjectsFullList = this.SGET_allDocuments.docs
  }

  async removeInput (scope: {
    index: number
    removeAtIndex: (index: number) => void
  }) {
    scope.removeAtIndex(scope.index)

    await this.$nextTick()
    /*eslint-disable */
    // @ts-ignore 
    this.$refs.ref_deleteDocument.hidePopup() 
    /* eslint-enable */
  }

  deleteOngoing = false

  deletedDocuments = 0

  currentDocName = ""

  currentDocument = null as unknown as I_ShortenedDocument

  get progressCounter () {
    return (this.deletedDocuments / this.deleteDocumentsModel.length)
  }

  async deleteDocuments () {
    this.deleteOngoing = true
    this.deletedDocuments = 0

    for (const document of this.deleteDocumentsModel) {
      this.currentDocName = document.label

      window.FA_dbs[document.type] = new PouchDB(document.type)

      // eslint-disable-next-line @typescript-eslint/no-unsafe-call
      this.currentDocument = await window.FA_dbs[document.type].get(document._id)

      // eslint-disable-next-line @typescript-eslint/no-unsafe-call
      await window.FA_dbs[document.type].remove(this.currentDocument)

      const dataPass = { doc: this.currentDocument, treeAction: true }

      this.currentDocument = this.SGET_document(document._id)

      // @ts-ignore
      this.SSET_removeOpenedDocument(dataPass)
      // @ts-ignore
      this.SSET_removeDocument({ doc: this.currentDocument })

      this.deletedDocuments++
    }

    // Cleanup
    this.deleteOngoing = false
    this.resetLocalData()
    this.populateDeleteObjectDialog()
    this.$q.notify({
      group: false,
      type: "positive",
      message: "Mass delete finished"
    })

    this.triggerDialogClose()
  }
}
</script>

<style lang="scss">
.deleteDialog {
  width: 750px;
  max-width: calc(100vw - 100px) !important;
  margin-top: 100px;
  align-self: flex-start;
  max-height: calc(100vh - 160px) !important;

  h6 {
    display: block;
  }

  .deleteDocumentSelect {
    width: calc(100% - 60px);
    margin-bottom: 30px;
  }
}
</style>
