import { Timestamp } from 'firebase/firestore'

/**
 * @param {date} payload
 * @param {string} format YYYY/MM/DD hh:mm:ss:SSS
 * @returns {string}
 */
export const funDateformat = (payload: Date | Timestamp | undefined | null, format: string) => {
  if (!payload) return ''

  if (payload instanceof Timestamp) {
    payload = payload.toDate()
  }

  format = format.replace(/YYYY/g, payload.getFullYear().toString())
  format = format.replace(/MM/g, ('0' + (payload.getMonth() + 1)).slice(-2))
  format = format.replace(/DD/g, ('0' + payload.getDate()).slice(-2))
  format = format.replace(/hh/g, ('0' + payload.getHours()).slice(-2))
  format = format.replace(/mm/g, ('0' + payload.getMinutes()).slice(-2))
  format = format.replace(/ss/g, ('0' + payload.getSeconds()).slice(-2))
  format = format.replace(/SSS/g, ('00' + payload.getMilliseconds()).slice(-3))
  return format
}

import { ref } from 'vue'

/**
 * スピナー
 */
export const isSpinner = ref(false)

/**
 * プログレス
 */
export const numProgress = ref(0)

// @ts-nocheck

export const fileToBlobUrl = (file: File) => {
  return window.URL.createObjectURL(file)
}

export const imageDataURLToFile = (dataUrl, fileName, mimeType) => {
  return fetch(dataUrl)
    .then((res) => res.arrayBuffer())
    .then((buf) => new File([buf], fileName, { type: mimeType }))
}

/**
 *
 * @param pdfFile
 * @param id
 * @returns
 */
export const generateThumbnailFromPDF = async (pdfFile: File, id: string) => {
  const pdfjs = await import('pdfjs-dist/build/pdf')
  const pdfjsWorker = await import('pdfjs-dist/build/pdf.worker.entry')
  pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker
  const pdf = await pdfjs.getDocument(fileToBlobUrl(pdfFile)).promise

  const firstPage = await pdf.getPage(1)
  const scale = 1.0
  const viewport = firstPage.getViewport({ scale: scale })

  // Prepare canvas using PDF page dimensions
  const canvas = document.createElement('canvas')
  canvas.id = `pdf_thumbnail${id}`
  const context = canvas.getContext('2d')
  canvas.height = viewport.height
  canvas.width = viewport.width

  const renderContext = {
    canvasContext: context,
    viewport: viewport,
  }

  await firstPage.render(renderContext).promise
  // return canvas.toDataURL()

  const genFile = await imageDataURLToFile(canvas.toDataURL(), 'temp_thumbnail.png', 'image/png')

  return URL.createObjectURL(genFile)
}
