package com.webtoonviewer.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Environment
import java.io.File
import java.io.FileInputStream

class ExternalStorageHelper {

    private val baseDir = File(Environment.getExternalStorageDirectory(), "Webtoon")
    private val baseTempDir = File(Environment.getExternalStorageDirectory(), "Temp_Webtoon")

    fun hasTempWebtoon(): Boolean {
        return baseTempDir.exists()
    }

    fun getAllWebtoonTitles(): MutableList<String> {
        return getAllWebtoonTitles(baseDir)
    }

    fun getAllTempWebtoonTitles(): MutableList<String> {
        return getAllWebtoonTitles(baseTempDir)
    }

    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 getAllEpisodes(title: String): MutableList<String> {
        val webtoonDir = File(baseDir, title)
        val episodes = mutableListOf<String>()
        val items = webtoonDir.listFiles()
        if (items != null) {
            for (item in items) {
                if (item.isDirectory) {
                    episodes.add(item.name)
                }
            }
        }
        return episodes
    }

    fun getImagePaths(title: String, episode: String): MutableList<File> {
        val episodeDir = File(baseDir, "$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
    }

    fun createEpisode(title: String, episode: String) {
        val file = File(baseDir, "$title/$episode")
        if (!file.exists()) {
            file.mkdirs()
        }
    }

    fun episodeExists(title: String, episode: String): Boolean {
        return File(baseDir, "$title/$episode").exists()
    }

    fun generateOutputFile(imagePath: String): File? {
        val parts = imagePath.split("/")
        return if (parts.size > 1) {
            val result = parts.drop(1).joinToString("/")
            return File(baseDir, result)
        } else null

    }
}