package com.mxn.helper.screenshot.server.controller

import android.content.Context
import android.util.Log
import com.mxn.helper.screenshot.helper.AppConfigHelper
import com.mxn.helper.screenshot.server.resp.ImageFileItemResp
import com.mxn.helper.screenshot.server.resp.ImageFileListResp
import com.mxn.helper.screenshot.server.resp.ImageFileRootResp
import com.mxn.helper.screenshot.utils.FileUtils
import com.mxn.helper.screenshot.utils.ZipUtils
import java.io.File
import java.net.URLDecoder
import java.text.SimpleDateFormat
import java.util.*

class ImageController(private val context: Context) : BaseController() {

    /**
     * 获取图片列表
     */
    fun getImageList(): String {
        val imageFiles = mutableListOf<ImageFileRootResp>()
        val filesDir = File(context.filesDir, "images")
        val localPath = context.filesDir.absolutePath
        val fileList = filesDir?.listFiles()
        var totalCount = 0
        fileList?.apply {
            this.sortBy { -it.lastModified() }
            totalCount = this.size
            imageFiles.add(ImageFileRootResp(mutableListOf()))
        }?.forEachIndexed { index, it ->
            val last = imageFiles.last()
            val imageUrl =
                AppConfigHelper.getLocalHostUrl(context) + "/file" + it.absolutePath.replace(
                    localPath, ""
                )
            last.images.add(
                ImageFileItemResp(
                    it.name.substring(0, it.name.length - 4),
                    imageUrl,
                    it.absolutePath
                )
            )
            if (last.images.size < 3) {

            } else {
                if (index != fileList.size - 1) imageFiles.add(ImageFileRootResp(mutableListOf()))
            }
        }
        return toJsonResponse(ImageFileListResp(imageFiles, totalCount))
    }

    fun createImage(): String {
        try {
            val dateFormat = SimpleDateFormat("yyyyMMddHHmmsss")
            // 将时间戳转换为 Date 对象
            val date = Date(System.currentTimeMillis())
            // 将 Date 对象格式化为时间字符串
            val dateString: String = dateFormat.format(date)
            val imageFilePath = File(context.filesDir, "images")
            Log.e("HHHHHH",imageFilePath.absolutePath)
            if (!imageFilePath.exists()) {
                imageFilePath.mkdirs()
            }
            val process = Runtime.getRuntime().exec(
                "screencap -p " + File(
                    imageFilePath, "screenshot_" + dateString + ".png"
                )
            )
            process.waitFor()
            Log.e("HHHHH", "命令执行完成")
        } catch (e: Throwable) {
            e.printStackTrace()
        }
        return toJsonResponseOnlyOK()
    }

    fun deleteImage(path: String): String {
        File(path).delete()
        return toJsonResponseOnlyOK()
    }

    fun zipImages(): String {
        val sourceFolderPath = File(context.filesDir, "images").absolutePath
        val aimFile = File(context.filesDir, "zip")
        if (!aimFile.exists()) {
            aimFile.mkdirs()
        }
        val fileName = System.currentTimeMillis().toString() + ".zip"
        val zipFilePath = aimFile.absolutePath + "/" + fileName
        ZipUtils.zipFolder(sourceFolderPath, zipFilePath)
        val data = mutableMapOf<String, String>(
            "downloadUrl" to AppConfigHelper.getLocalHostUrl(context) + "/file/zip/" + fileName,
            "fileName" to fileName
        )
        return toJsonResponse(data)
    }

    fun clearAllFile(): String {
        val imageDir = File(context.filesDir, "images")
        val zipDir = File(context.filesDir, "zip")
        FileUtils.deleteFolder(imageDir)
        FileUtils.deleteFolder(zipDir)
        return toJsonResponseOnlyOK()
    }

    fun rename(path: String, newName: String): String {
        File(path)?.apply {
            if (this.exists()) {
                if (newName.endsWith(".png")) {
                    this.renameTo(File(this.parentFile.absoluteFile, "${
                        URLDecoder.decode(
                            newName,
                            "utf-8"
                        )}"))
                } else {
                    this.renameTo(File(this.parentFile.absoluteFile, "${URLDecoder.decode(
                        newName,
                        "utf-8"
                    )}.png"))
                }
            }
        }
        return toJsonResponseOnlyOK()
    }
}