package com.all.pdfreader.pro.app.util

import android.content.Context
import android.net.Uri
import android.graphics.pdf.PdfRenderer
import android.os.ParcelFileDescriptor
import java.io.File
import java.io.InputStream
import java.util.*

object PdfMetadataExtractor {

    data class PdfMetadata(
        val title: String?,
        val author: String?,
        val subject: String?,
        val keywords: String?,
        val creator: String?,
        val producer: String?,
        val creationDate: Date?,
        val modificationDate: Date?,
        val pageCount: Int,
        val fileSize: Long
    )

    fun extractMetadata(filePath: String): PdfMetadata? {
        return try {
            val file = File(filePath)
            if (!file.exists()) return null
            
            val fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
            extractFromFileDescriptor(fileDescriptor, file.length())
        } catch (e: Exception) {
            null
        }
    }

    fun extractMetadata(uri: Uri, context: Context): PdfMetadata? {
        return try {
            context.contentResolver.openFileDescriptor(uri, "r")?.use { fileDescriptor ->
                extractFromFileDescriptor(fileDescriptor, 0L)
            }
        } catch (e: Exception) {
            null
        }
    }

    private fun extractFromFileDescriptor(fileDescriptor: ParcelFileDescriptor, fileSize: Long): PdfMetadata? {
        return try {
            PdfRenderer(fileDescriptor).use { renderer ->
                val pageCount = renderer.pageCount
                
                // 使用文件基本信息
                PdfMetadata(
                    title = null,
                    author = null,
                    subject = null,
                    keywords = null,
                    creator = null,
                    producer = null,
                    creationDate = null,
                    modificationDate = null,
                    pageCount = pageCount,
                    fileSize = fileSize
                )
            }
        } catch (e: Exception) {
            null
        }
    }

    fun getBasicInfo(file: File): PdfMetadata? {
        return try {
            val fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
            PdfRenderer(fileDescriptor).use { renderer ->
                PdfMetadata(
                    title = null,
                    author = null,
                    subject = null,
                    keywords = null,
                    creator = null,
                    producer = null,
                    creationDate = null,
                    modificationDate = null,
                    pageCount = renderer.pageCount,
                    fileSize = file.length()
                )
            }
        } catch (e: Exception) {
            null
        }
    }

    fun extractThumbnail(filePath: String, outputPath: String): Boolean {
        return try {
            val file = File(filePath)
            if (!file.exists()) return false
            
            val fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
            PdfRenderer(fileDescriptor).use { renderer ->
                if (renderer.pageCount > 0) {
                    val page = renderer.openPage(0)
                    val bitmap = android.graphics.Bitmap.createBitmap(
                        page.width,
                        page.height,
                        android.graphics.Bitmap.Config.ARGB_8888
                    )
                    page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
                    page.close()
                    
                    java.io.FileOutputStream(outputPath).use { fos ->
                        bitmap.compress(android.graphics.Bitmap.CompressFormat.JPEG, 80, fos)
                    }
                    bitmap.recycle()
                    true
                } else {
                    false
                }
            }
        } catch (e: Exception) {
            false
        }
    }

    fun isValidPdf(file: File): Boolean {
        return try {
            val fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
            PdfRenderer(fileDescriptor).use { renderer ->
                renderer.pageCount > 0
            }
        } catch (e: Exception) {
            false
        }
    }

    fun sanitizeFilename(filename: String): String {
        return filename.replace(Regex("[\\\\/:*?\"\u003c\u003e|]"), "_").trim()
    }

    fun extractTitleFromFilename(filename: String): String {
        return filename.removeSuffix(".pdf").removeSuffix(".PDF")
    }

    fun formatDate(date: Date?): String {
        return date?.let {
            val calendar = Calendar.getInstance()
            calendar.time = it
            String.format(Locale.US, "%04d-%02d-%02d", 
                calendar.get(Calendar.YEAR), 
                calendar.get(Calendar.MONTH) + 1, 
                calendar.get(Calendar.DAY_OF_MONTH))
        } ?: ""
    }
}