package com.ux.video.file.filerecovery.utils

import android.content.Context
import android.content.Intent
import android.icu.util.Calendar
import android.os.Build
import android.os.Parcelable
import android.util.TypedValue
import androidx.recyclerview.widget.RecyclerView
import com.ux.video.file.filerecovery.db.ResultDataFiles
import com.ux.video.file.filerecovery.db.duration
import com.ux.video.file.filerecovery.db.isThumbnail
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.Date

object ExtendFunctions {


    fun Int.dpToPx(context: Context): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            this.toFloat(),
            context.resources.displayMetrics
        ).toInt()
    }

    inline fun <reified T : Parcelable> Intent.getParcelableArrayListExtraCompat(key: String): ArrayList<T>? {
        extras?.classLoader = T::class.java.classLoader

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            getParcelableArrayListExtra(key, T::class.java)
        } else {
            @Suppress("DEPRECATION")
            getParcelableArrayListExtra<T>(key)
        }
    }

    fun RecyclerView.resetItemDecorationOnce(decoration: RecyclerView.ItemDecoration) {
        while (itemDecorationCount > 0) {
            removeItemDecorationAt(0)
        }
        addItemDecoration(decoration)
    }


    fun List<ResultDataFiles>.filterWithinDateRangeList(
        months: Int = -1,
        startDate: Date? = null,
        endDate: Date? = null
    ): List<ResultDataFiles> {

        val today = Calendar.getInstance()

        return when {

            months == -1 -> this

            months == 0 -> this.filter { file ->
                val date = Date(file.lastModified)
                when {
                    startDate != null && endDate != null -> date in startDate..endDate
//                    startDate != null -> !date.before(startDate)
//                    endDate != null -> !date.after(endDate)
                    else -> true // 没传日期则默认不过滤
                }
            }

            else -> {
                val monthsAgo = Calendar.getInstance().apply {
                    add(Calendar.MONTH, -months)
                }

                this.filter { file ->
                    val cal = Calendar.getInstance().apply { timeInMillis = file.lastModified }
                    !cal.before(monthsAgo) && !cal.after(today)
                }
            }
        }
    }





    fun List<Pair<String, List<ResultDataFiles>>>.filterWithinDateRange(
        months: Int = -1,
        startDate: Date? = null,
        endDate: Date? = null
    ): List<Pair<String, List<ResultDataFiles>>> {

        val sdf = Common.dateFormat
        val today = Calendar.getInstance()

        // 计算“几个月前”的时间
        val monthsAgo = Calendar.getInstance().apply {
            add(Calendar.MONTH, -months)
        }

        return when {

            months == -1 -> this


            months == 0 -> this.filter { (dayStr, _) ->
                val day = sdf.parse(dayStr) ?: return@filter false
                when {
                    startDate != null && endDate != null -> day in startDate..endDate
//                    startDate != null -> !day.before(startDate)
//                    endDate != null -> !day.after(endDate)
                    else -> true // 没传 start/end 则默认不过滤
                }
            }


            else -> this.filter { (dayStr, _) ->
                val day = sdf.parse(dayStr) ?: return@filter false
                !day.before(monthsAgo.time) && !day.after(today.time)
            }
        }
    }
    /**
     * 按文件大小筛选：区间 [minSize, maxSize]
     */
    fun List<ResultDataFiles>.filterBySizeList(
        minSize: Long,
        maxSize: Long
    ): List<ResultDataFiles> {
        if (minSize == -1L) return this
        return this.filter { it.size in minSize..maxSize }
    }

    /**
     * 按文件大小筛选：区间 [minSize, maxSize]
     */
    fun List<ResultDataFiles>.filterByDurationList(
        minSize: Long,
        maxSize: Long
    ): List<ResultDataFiles> {
        if (minSize == -1L) return this
        return this.filter { it.duration() in minSize..maxSize }
    }

    /**
     * 分组数据：按大小筛选 ,图片和文件筛选文件大小
     */
    fun List<Pair<String, List<ResultDataFiles>>>.filterBySize(
        minSize: Long,
        maxSize: Long
    ): List<Pair<String, List<ResultDataFiles>>> {
        if (minSize == -1L) return this
        return this.mapNotNull { (date, files) ->
            val filtered = files.filter { it.size in minSize..maxSize }
            if (filtered.isNotEmpty()) date to filtered else null
        }
    }

    /**
     * 分组数据：按大小筛选 ,音视频筛选时长
     */
    fun List<Pair<String, List<ResultDataFiles>>>.filterByDuration(
        minSize: Long,
        maxSize: Long
    ): List<Pair<String, List<ResultDataFiles>>> {
        if (minSize == -1L) return this
        return this.mapNotNull { (date, files) ->
            val filtered = files.filter { it.duration() in minSize..maxSize }
            if (filtered.isNotEmpty()) date to filtered else null
        }
    }


    fun Int.mbToBytes(): Long {
        return this * 1000L * 1000L
    }

    fun Int.kbToBytes(): Long {
        return this * 1000L
    }

    fun Int.minutesToMillisecond(): Long {
        return this * 60 * 1000L
    }

    /**
     * 移除掉缩略图后的数据
     */
    suspend fun List<Pair<String, List<ResultDataFiles>>>.filterThumbnailsAsync(): List<Pair<String, List<ResultDataFiles>>> =
        withContext(Dispatchers.Default) {
            this@filterThumbnailsAsync.asSequence()
                .mapNotNull { (key, files) ->
                    val filtered = files.asSequence().filter { !it.isThumbnail() }.toList()
                    if (filtered.isNotEmpty()) key to filtered else null
                }
                .toList()
        }


    /**
     * 移除掉缩略图后的数据
     */
    suspend fun List<ResultDataFiles>.filterRemoveThumbnailsAsync(): List<ResultDataFiles> =
        withContext(Dispatchers.Default) {
            this@filterRemoveThumbnailsAsync.asSequence()
                .filter { !it.isThumbnail() } // 去掉 isThumbnail = true 的项
                .toList()
        }


    fun List<Pair<String, List<ResultDataFiles>>>.removeItem(
        target: ResultDataFiles
    ): List<Pair<String, List<ResultDataFiles>>> {
        return this.mapNotNull { (key, files) ->
            val updatedFiles = files.filterNot { it == target }
            if (updatedFiles.isNotEmpty()) key to updatedFiles else null
        }
    }


}