package com.webtoonviewer.storage

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import com.webtoonviewer.ui.data.FileItem
import java.io.File
import java.io.FileInputStream
import java.io.IOException

object StorageManager {

    private fun getWebtoonDir(context: Context): File {
        return File(context.filesDir, "Webtoon")
    }

    // 检查指定目录是否存在
    fun isDirectoryExists(context: Context, dirName: String): Boolean {
        val directory = File(getWebtoonDir(context), dirName)
        return directory.exists() && directory.isDirectory
    }

    // 创建目录
    fun createDirectory(context: Context, dirName: String) {
        val directory = File(getWebtoonDir(context), dirName)
        if (!directory.exists()) {
            directory.mkdirs() // 创建目录及其子目录
        }
    }

    // 删除目录及其内容
    fun deleteDirectory(context: Context, dirPath: String): Boolean {
        val directory = File(dirPath)
        return deleteRecursive(directory)
    }

    // 递归删除文件和目录
    private fun deleteRecursive(fileOrDirectory: File): Boolean {
        if (fileOrDirectory.isDirectory) {
            fileOrDirectory.listFiles()?.forEach { child ->
                if (!deleteRecursive(child)) {
                    return false
                }
            }
        }
        return fileOrDirectory.delete()
    }

    // 获取目录下的文件列表
    fun getFilesAndDirectory(context: Context, dirPath: String): MutableList<FileItem> {
        val directory = if (dirPath == "") {
            context.filesDir
        } else {
            File(dirPath)
        }
        val fileItems = mutableListOf<FileItem>()

        directory.listFiles()?.forEach { file ->
            fileItems.add(FileItem(file.name, file.isDirectory, file.absolutePath))
        }
        return fileItems
    }

    fun getFilesAndDirectorySum(context: Context, dirPath: String): Int {
        val directory = if (dirPath == "") {
            context.filesDir
        } else {
            File(dirPath)
        }
        return directory.listFiles()?.size ?: 0
    }

    fun getAllWebtoonTitles(context: Context): MutableList<String> {
        return getAllWebtoonTitles(getWebtoonDir(context))
    }

    private fun getAllWebtoonTitles(dir: File): MutableList<String> {
        val titles = mutableListOf<String>()
        val items = dir.listFiles()
        if (items != null) {
            for (item in items) {
                if (item.isDirectory) {
                    titles.add(item.name)
                }
            }
        }
        return titles
    }

    // 读取文件内容
    fun readFile(context: Context, dirName: String, fileName: String): String? {
        val directory = File(context.filesDir, dirName)
        val file = File(directory, fileName)
        return if (file.exists()) {
            file.readText()
        } else {
            null // 文件不存在时返回null
        }
    }

    fun generateOutputFile(context: Context, imagePath: String): File {
        // imagePath: Webtoon/title/episode/image.jpg
        return File(context.filesDir, imagePath)
    }

    fun getImagePaths(context: Context, title: String, episode: String): MutableList<File> {
        val episodeDir = File(getWebtoonDir(context), "$title/$episode")
        val imagePaths = mutableListOf<File>()
        val items = episodeDir.listFiles()
        val sum = items?.size ?: 0
        for (i in 1 until sum + 1) {
            imagePaths.add(File(episodeDir,"$i.jpg"))
        }
        return imagePaths
    }

    fun loadImage(imagePath: File): Bitmap? {
        return if (imagePath.exists()) {
            val inputStream = FileInputStream(imagePath)
            val bytes = inputStream.readBytes()
            inputStream.close()
            BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
        } else null
    }
}