import JSZip from 'jszip'
import { toast } from 'react-toastify'
import { InputFileFormat, OutputByType, OutputType } from '../types'

/**
 * Read the content of a file within a zip archive.
 * @param zip The JSZip object representing the zip archive.
 * @param filePath The path of the file within the zip archive.
 * @param outputType The type of output to return (e.g., 'string', 'arraybuffer', 'uint8array', etc.).
 * @returns A Promise resolving to the content of the file, or null if an error occurs.
 */
const readContentOfZipEntry = async <T extends OutputType>(
  zip: JSZip,
  filePath: string,
  outputType: T
): Promise<OutputByType[T] | null> => {
  // Get the zip entry corresponding to the specified file path
  const zipEntry = zip.files[filePath]

  if (!zipEntry) {
    toast.error(`Couldn't find file in zip archive at ${filePath}`)
    return null
  }

  // Read and return the content of the zip entry asynchronously
  // or null if an error has occurred
  return await zipEntry.async(outputType).catch((err) => {
    // Handle any errors that occur during the read operation
    console.log(`Error reading content of ${filePath}:`, err)
    toast.error(
      err.message || `Error occurred in reading content of ${filePath}`
    )
    return null
  })
}

const loadZip = async (data: InputFileFormat): Promise<JSZip | null> => {
  try {
    return await JSZip.loadAsync(data)
  } catch (err) {
    console.log('err in loading zip file :>> ', err)
    if (err instanceof Error) {
      toast.error(err.message || 'An error occurred in loading zip file.')
    }
    return null
  }
}

export { readContentOfZipEntry, loadZip }
