package com.base.superfilemanager.fragment

import android.annotation.SuppressLint
import android.app.usage.UsageEvents
import android.app.usage.UsageEvents.Event.ACTIVITY_PAUSED
import android.app.usage.UsageEvents.Event.ACTIVITY_RESUMED
import android.app.usage.UsageEvents.Event.FOREGROUND_SERVICE_START
import android.graphics.Typeface
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import com.base.superfilemanager.R
import com.base.superfilemanager.activity.RecentAppActivity
import com.base.superfilemanager.adapter.RecentAppAdapter
import com.base.superfilemanager.bean.AppBean
import com.base.superfilemanager.databinding.FragmentLaunchesBinding
import com.base.superfilemanager.helps.BaseFragment
import com.base.superfilemanager.helps.LogEx
import com.base.superfilemanager.helps.TimeUtils
import com.base.superfilemanager.helps.TimeUtils.PAST_60_MINUS_QUERY
import com.base.superfilemanager.helps.TimeUtils.SEVEN_DAYS_QUERY
import com.base.superfilemanager.helps.TimeUtils.TODAY_QUERY
import com.base.superfilemanager.helps.TimeUtils.YESTERDAY_QUERY
import com.base.superfilemanager.view.TimeSelectDialog.showTimeSelectDialog
import java.text.SimpleDateFormat
import kotlin.time.Duration.Companion.hours
import kotlin.time.DurationUnit


class LaunchesFragment : BaseFragment<FragmentLaunchesBinding>() {

    private val TAG = "LaunchesFragment"
    private var dataList = arrayListOf<AppBean>()
    private lateinit var adapter: RecentAppAdapter

    @SuppressLint("SimpleDateFormat")
    private var simpleDateFormat2 = SimpleDateFormat("(yyyy/MM/dd)")
    private var UI_MODE = UI_MODE_ALL


    override val binding: FragmentLaunchesBinding by lazy {
        FragmentLaunchesBinding.inflate(layoutInflater)
    }

    override fun setView() {
        setTextFont()
        adapter = RecentAppAdapter(requireActivity(), RecentAppAdapter.UI_LAUNCHES_MODE)
        binding.rv.adapter = adapter
    }

    override fun setListener() {
        binding.clLaunches.setOnClickListener {
            launchesMode()
        }

        binding.clForeground.setOnClickListener {
            foregroundMode()
        }

        binding.clBackground.setOnClickListener {
            backgroundMode()
        }
        binding.llDate.setOnClickListener {
            requireContext().showTimeSelectDialog {
                when (it) {
                    PAST_60_MINUS_QUERY -> {
                        recent60UI()
                    }

                    TODAY_QUERY -> {
                        todayUI()
                    }

                    YESTERDAY_QUERY -> {
                        yesterdayUI()
                    }

                    SEVEN_DAYS_QUERY -> {
                        sevenDaysUI()
                    }
                }
            }
        }


        todayUI(false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }


    override fun onResume() {
        super.onResume()
    }

    @SuppressLint("SetTextI18n")
    fun todayUI(isReFresh: Boolean = true) {
        binding.tvDate.text = "Today" + simpleDateFormat2.format(System.currentTimeMillis())
        if (isReFresh) {
            (requireActivity() as RecentAppActivity).changeTimeRefresh(TODAY_QUERY, 0)
        }
    }

    @SuppressLint("SetTextI18n")
    fun recent60UI(isReFresh: Boolean = true) {
        binding.tvDate.text = "Recent 60 minus"
        if (isReFresh) {
            (requireActivity() as RecentAppActivity).changeTimeRefresh(PAST_60_MINUS_QUERY, 0)
        }
    }

    @SuppressLint("SetTextI18n")
    fun yesterdayUI(isReFresh: Boolean = true) {
        binding.tvDate.text =
            "Yesterday" + simpleDateFormat2.format(System.currentTimeMillis() - 24.hours.toLong(DurationUnit.MILLISECONDS))
        if (isReFresh) {
            (requireActivity() as RecentAppActivity).changeTimeRefresh(YESTERDAY_QUERY, 0)
        }
    }

    @SuppressLint("SetTextI18n")
    fun sevenDaysUI(isReFresh: Boolean = true) {
        binding.tvDate.text = "Last 7 days"
        if (isReFresh) {
            (requireActivity() as RecentAppActivity).changeTimeRefresh(SEVEN_DAYS_QUERY, 0)
        }
    }

    private fun filterRv() {
        adapter.setNumberMode(UI_MODE)
        when (UI_MODE) {
            UI_MODE_ALL -> {
                val data = dataList.filter { it.launchTimes > 0 }
                adapter.setData(data)
            }

            UI_MODE_FOREGROUND -> {
                val data = dataList.filter { it.foregroundTimes > 0 }
                adapter.setData(data)
            }

            UI_MODE_BACKGROUND -> {
                val data = dataList.filter { it.backgroundTimes > 0 }
                adapter.setData(data)
            }
        }
    }

    fun launchesMode() {
        foregroundEnable(false)
        backgroundEnable(false)
        launchesEnable(true)
        UI_MODE = UI_MODE_ALL
        filterRv()
    }

    fun foregroundMode() {
        launchesEnable(false)
        backgroundEnable(false)
        foregroundEnable(true)
        UI_MODE = UI_MODE_FOREGROUND
        filterRv()
    }

    fun backgroundMode() {
        launchesEnable(false)
        foregroundEnable(false)
        backgroundEnable(true)
        UI_MODE = UI_MODE_BACKGROUND
        filterRv()
    }

    fun launchesEnable(enable: Boolean) {
        if (enable) {
            val enableBorder =
                ContextCompat.getDrawable(requireContext(), R.drawable.bg_corners_recent)
            binding.ivLaunchesBorder.background = enableBorder
            binding.ivLaunchesTriangle.visibility = View.VISIBLE
            binding.tvLaunchesNumber.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.white
                )
            )
            binding.tvLaunches.setTextColor(ContextCompat.getColor(requireContext(), R.color.white))
        } else {
            val disableBorder =
                ContextCompat.getDrawable(requireContext(), R.drawable.bg_stroke_e3e5ea)
            binding.ivLaunchesBorder.background = disableBorder
            binding.ivLaunchesTriangle.visibility = View.GONE
            binding.tvLaunchesNumber.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.black
                )
            )
            binding.tvLaunches.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.color_999999
                )
            )
        }
    }

    fun foregroundEnable(enable: Boolean) {
        if (enable) {
            val enableBorder =
                ContextCompat.getDrawable(requireContext(), R.drawable.bg_corners_recent)
            binding.ivForegroundBorder.background = enableBorder
            binding.ivForegroundTriangle.visibility = View.VISIBLE
            binding.tvForegroundNumber.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.white
                )
            )
            binding.tvForeground.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.white
                )
            )
        } else {
            val disableBorder =
                ContextCompat.getDrawable(requireContext(), R.drawable.bg_stroke_e3e5ea)
            binding.ivForegroundBorder.background = disableBorder
            binding.ivForegroundTriangle.visibility = View.GONE
            binding.tvForegroundNumber.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.black
                )
            )
            binding.tvForeground.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.color_999999
                )
            )
        }
    }

    fun backgroundEnable(enable: Boolean) {
        if (enable) {
            val enableBorder =
                ContextCompat.getDrawable(requireContext(), R.drawable.bg_corners_recent)
            binding.ivBackgroundBorder.background = enableBorder
            binding.ivBackgroundTriangle.visibility = View.VISIBLE
            binding.tvBackgroundNumber.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.white
                )
            )
            binding.tvBackground.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.white
                )
            )
        } else {
            val disableBorder =
                ContextCompat.getDrawable(requireContext(), R.drawable.bg_stroke_e3e5ea)
            binding.ivBackgroundBorder.background = disableBorder
            binding.ivBackgroundTriangle.visibility = View.GONE
            binding.tvBackgroundNumber.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.black
                )
            )
            binding.tvBackground.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.color_999999
                )
            )
        }
    }


    private fun setTextFont() {
        val fontMedium = "sans-serif-medium"
        val fontMediumTypeface = Typeface.create(fontMedium, Typeface.NORMAL)
        binding.tvDate.setTypeface(fontMediumTypeface)
    }

    /**
     * 更新数据
     */
    fun setAppUseData(dataList: List<AppBean>) {
        LogEx.logDebug(TAG, "setAppUseData")
        this.dataList.clear()
        this.dataList.addAll(dataList)
        //setLaunchNumber()
        if (isVisible) {
            setLaunchNumber2()
            launchesMode()
        }
    }


    private fun setLaunchNumber2() {
        dataList.forEach { app ->
            app.foregroundTimes = app.usageEvents?.filter { it.eventType == 1 }?.size ?: 0
            app.backgroundTimes = app.usageEvents?.filter { it.eventType == 19 }?.size ?: 0
            app.launchTimes = app.foregroundTimes + app.backgroundTimes
        }

        val totalNumber = dataList.sumOf { it.launchTimes }
        val foregroundNumber = dataList.sumOf { it.foregroundTimes }
        val backgroundNumber = dataList.sumOf { it.backgroundTimes }

        binding.tvLaunchesNumber.text = totalNumber.toString()
        binding.tvForegroundNumber.text = foregroundNumber.toString()
        binding.tvBackgroundNumber.text = backgroundNumber.toString()
    }

    /**
     * 旧的计算前台后台数量逻辑
     */
    @SuppressLint("InlinedApi")
    private fun setLaunchNumber() {

        val tempList = ArrayList<UsageEvents.Event>()


        dataList.forEach { app ->

            app.usageEvents?.let { events ->


                tempList.clear()
                tempList.addAll(events)

                tempList.forEachIndexed { index, event ->

                    if (app.pkg == "tv.danmaku.bili") {
                        LogEx.logDebug(
                            TAG, "$index ${event.packageName} " +
                                    TimeUtils.simpleDateFormat.format(event.timeStamp) +
                                    " ${event.eventType}"
                        )
                    }

                    //后台启动次数
                    if (event.eventType == FOREGROUND_SERVICE_START) {
                        app.backgroundTimes++
                    }


                    //上一个事件
                    val lastIndex = index - 1
                    var lastEvent: UsageEvents.Event? = null
                    if (lastIndex >= 0) {
                        lastEvent = tempList[lastIndex]
                    }

                    //上面是欧拉的前台判断逻辑 event上次 event2本次
                    // (event == null || !Objects.equals(event.getPackageName(), event2.getPackageName()))
                    //       &&
                    //((event == null || event.getEventType() == 2) && event2.getEventType() == 1)

                    if (event.eventType == ACTIVITY_RESUMED) {

                        val flag1 =
                            lastEvent == null || ((lastEvent.packageName != app.pkg) && (lastEvent.eventType == ACTIVITY_PAUSED))
                        val flag2 = (lastEvent != null) && (lastEvent.packageName != app.pkg)

                        if (flag1) {
                            app.foregroundTimes++

                            if (app.pkg == "tv.danmaku.bili") {
                                LogEx.logDebug(TAG, "前台加一 flag1 ${app.foregroundTimes}")
                            }

                        } else if (flag2) {
                            app.foregroundTimes++

                            if (app.pkg == "tv.danmaku.bili") {
                                LogEx.logDebug(TAG, "前台加一 flag2 ${app.foregroundTimes}")
                            }
                        }
                    }
                }
            }

            //2的阈值
            if (app.foregroundTimes < 2) {
                app.foregroundTimes = 0
            }
            app.launchTimes = app.foregroundTimes + app.backgroundTimes

            if (app.pkg == "tv.danmaku.bili") {
                LogEx.logDebug(
                    TAG, "${app.pkg} launchTimes=${app.launchTimes} " +
                            "foregroundTimes=${app.foregroundTimes} " +
                            "backgroundTimes=${app.backgroundTimes}"
                )
            }

        }

        val totalNumber = dataList.sumOf { it.launchTimes }
        val foregroundNumber = dataList.sumOf { it.foregroundTimes }
        val backgroundNumber = dataList.sumOf { it.backgroundTimes }

        binding.tvLaunchesNumber.text = totalNumber.toString()
        binding.tvForegroundNumber.text = foregroundNumber.toString()
        binding.tvBackgroundNumber.text = backgroundNumber.toString()
    }

    companion object {
        const val UI_MODE_ALL = 5
        const val UI_MODE_FOREGROUND = 25
        const val UI_MODE_BACKGROUND = 35
    }


}