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.photo.ResultPhotosFiles
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>? {
        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)
    }


    /**
     * 按时间筛选：最近 N 个月
     */
//    fun List<ResultPhotosFiles>.filterWithinMonthsList(months: Int): List<ResultPhotosFiles> {
//        if (months == -1) return this
//        val today = Calendar.getInstance()
//        val monthsAgo = Calendar.getInstance().apply {
//            add(Calendar.MONTH, -months)
//        }
//        return this.filter {
//            val cal = Calendar.getInstance().apply { timeInMillis = it.lastModified }
//            !cal.before(monthsAgo) && !cal.after(today)
//        }
//    }

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

        val today = Calendar.getInstance()

        return when {
            // ✅ 1. -1 表示不过滤，返回全部
            months == -1 -> this

            // ✅ 2. 0 表示仅根据 startDate / endDate 筛选
            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 // 没传日期则默认不过滤
                }
            }

            // ✅ 3. 其他情况：按“最近 N 个月”筛选
            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)
                }
            }
        }
    }




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

    /**
     * 按时间筛选：最近 N 个月
     */
//    fun List<Pair<String, List<ResultPhotosFiles>>>.filterWithinMonths(months: Int): List<Pair<String, List<ResultPhotosFiles>>> {
//        if (months == -1) return this
//        val sdf = Common.dateFormat
//        val today = Calendar.getInstance()
//        val monthsAgo = Calendar.getInstance().apply {
//            add(Calendar.MONTH, -months)
//        }
//        return this.filter { (dayStr, _) ->
//            val day = sdf.parse(dayStr)
//            day != null && !day.before(monthsAgo.time) && !day.after(today.time)
//        }
//    }
    fun List<Pair<String, List<ResultPhotosFiles>>>.filterWithinDateRange(
        months: Int = -1,
        startDate: Date? = null,
        endDate: Date? = null
    ): List<Pair<String, List<ResultPhotosFiles>>> {

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

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

        return when {
            //  -1 表示不过滤，返回全部
            months == -1 -> this

            //  0 表示只用日期范围过滤
            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 则默认不过滤
                }
            }

            //  其他情况：按“最近 N 个月”过滤
            else -> this.filter { (dayStr, _) ->
                val day = sdf.parse(dayStr) ?: return@filter false
                !day.before(monthsAgo.time) && !day.after(today.time)
            }
        }
    }







    /**
     * 分组数据：按大小筛选
     */
    fun List<Pair<String, List<ResultPhotosFiles>>>.filterBySize(
        minSize: Long,
        maxSize: Long
    ): List<Pair<String, List<ResultPhotosFiles>>> {
        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 Int.mbToBytes(): Long {
        return this * 1024L * 1024L
    }


}