<script setup>
import { date, string } from 'alga-js'
import { toast } from 'bulma-toast'

const printPreview = usePrintPreview()
const printParam = usePrintParam()
const user = useCookie('logship_user')

const props = defineProps({
  modelName: String 
})

const pdfSrc = ref('')
const pdfPreview = async () => {
  const response = await $fetch('/api/'+props.modelName+'/'+printParam.value.id+'/print/PDF', {
    headers: useRequestHeaders(['cookie'])
  })
  if(response?.reportFile) {
    const base64Response = await fetch(`data:application/pdf;base64,${response.reportFile}`);
    const blob = await base64Response.blob();
    pdfSrc.value = URL.createObjectURL(blob)
  }
}
watch(printPreview, pdfPreview)

const closePrintPreview = () => {
  printPreview.value = false
  pdfSrc.value = ''
  printParam.value = {}
}

const printReport = async (fileType) => {
  const response = await $fetch('/api/'+props.modelName+'/'+printParam.value.id+'/print/'+fileType, {
    headers: useRequestHeaders(['cookie'])
  })
  if(response) {
    let mimeType = ''
    let blob = new Blob([])
    if(fileType === 'PDF') {
      mimeType = 'application/pdf'
      const base64Response = await fetch(`data:${mimeType};base64,${response.reportFile}`);
      blob = await base64Response.blob();
    } else if(fileType === 'HTML') {
      mimeType = 'text/html'
      blob = new Blob([atob(response.exportFile)], {type: mimeType})
    } else if(fileType === 'CSV') {
      mimeType = 'text/csv'
      blob = new Blob([atob(response.exportFile)], {type: mimeType})
    } else if(fileType === 'XLSX') {
      mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      blob = new Blob([atob(response.exportFile)], {type: mimeType})
    } else if(fileType === 'XLS') {
      mimeType = 'application/vnd.ms-excel'//data:application/octet-stream;base64
      blob = new Blob([atob(response.exportFile)], {type: mimeType})
    }
    const blobUrl = URL.createObjectURL(blob)
    open(blobUrl, '_blank')
  }
}

const serverSidePrinting = async (content) => {
  const res = await $fetch('/api/print/', {
    method: 'POST',
    body: content
  })
  if(res) {
    console.log(res)
    if(res?.stdout) {
      toast({
        message: 'The document has been printed via server side printing!',
        type: 'is-success',
        duration: 2000
      })
    }
  }
}

const printServer = async () => {
  const response = await $fetch('/api/'+props.modelName+'/'+printParam.value.id+'/print/PDF', {
    headers: useRequestHeaders(['cookie'])
  })
  if(response) {
    serverSidePrinting({
      pathName: `${props.modelName?.replaceAll('/', '-')}/${new Date().getFullYear()}`,
      fileName: `${date.now().replace(/\-|\:/g, '_').replace(' ', '-'+printParam.value.documentNo+'-')}-${props.modelName?.replaceAll('/', '-')?.toUpperCase()}-${user.value?.Name || 'SUPERUSER'}.pdf`,
      fileContent: response.reportFile
    })
  }
}

const dropDownHandler = (e) => {
  if(e.target.parentElement.classList.contains('show')) {
    e.target.parentElement.classList.remove('show')
  } else {
    e.target.parentElement.classList.add('show')
  }
}

const dropItemHandler = (e) => {
  if(e.target.parentElement.parentElement.classList.contains('show')) {
    e.target.parentElement.parentElement.classList.remove('show')
  } else {
    e.target.parentElement.parentElement.classList.add('show')
  }
}
</script>

<template>
  <div class="modal" :class="{'active': printPreview}" :style="{display: printPreview ? 'block' : 'none'}">
    <div class="modalDialog modalCenter modalPrintPreview" @click.self="closePrintPreview">
      <div class="modalContent">
        <div class="modalHeader">
          <h3 class="modalTitle">Print Preview</h3>
          <div class="cursor-pointer" @click="closePrintPreview">
            <span class="tf-icon ti ti-x ti-sm me-1"></span>
          </div>
        </div>
        <div class="modalBody">
          <div class="d-flex justify-between mb-3">
            <h4></h4>
            <div class="d-flex gap-0.75rem">
              <div>
                <button type="button" class="button" @click="printServer">
                  <span class="tf-icon ti ti-printer ti-xs me-1 color-inherit"></span> Print Server
                </button>
              </div>
              <div class="dropDown">
                <button type="button" class="button dropDownToggler" @click="dropDownHandler">
                  <span class="tf-icon ti ti-file-export ti-xs me-1 color-inherit"></span> Print Report
                </button>
                <div class="dropDownBackdrop" @click="dropDownHandler"></div>
                <div class="dropDownMenu dropDownRight">
                  <span class="dropDownItem" @click="dropItemHandler($event); printReport('PDF');">Print Report in PDF</span>
                  <span class="dropDownItem" @click="dropItemHandler($event); printReport('HTML');">Print Report in HTML</span>
                  <span class="dropDownItem" @click="dropItemHandler($event); printReport('CSV');">Print Report in CSV</span>
                  <span class="dropDownItem" @click="dropItemHandler($event); printReport('XLSX');">Print Report in XLSX</span>
                  <span class="dropDownItem" @click="dropItemHandler($event); printReport('XLS');">Print Report in XLS</span>
                </div>
              </div>
            </div>
          </div>
          <div>
            <div class="my-5 mx-5">
              <ClientOnly v-if="pdfSrc !== ''">
                <PrintViewer :url="pdfSrc" />
              </ClientOnly>
            </div>
          </div>
        </div>
        <div class="modalFooter">
          <div></div>
          <div class="d-flex gap-10px">
            <button type="button" class="button" @click="closePrintPreview">Close</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal.active .modalDialog {
  padding: 0;
}
.modalContent {
  background: white;
}

/*@media (max-width: 900px) {
  margin-right: 8px;
}*/
</style>