package com.test.basd.smartjunkcleaner.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.test.basd.smartjunkcleaner.R
import com.test.basd.smartjunkcleaner.activity.RecentAppActivity
import com.test.basd.smartjunkcleaner.adapter.RecentAppAdapter
import com.test.basd.smartjunkcleaner.bean.AppBean
import com.test.basd.smartjunkcleaner.databinding.FragmentLaunchesBinding
import com.test.basd.smartjunkcleaner.helps.BaseFragment
import com.test.basd.smartjunkcleaner.helps.LogEx
import com.test.basd.smartjunkcleaner.helps.TimeUtils
import com.test.basd.smartjunkcleaner.helps.TimeUtils.PAST_60_MINUS_QUERY
import com.test.basd.smartjunkcleaner.helps.TimeUtils.SEVEN_DAYS_QUERY
import com.test.basd.smartjunkcleaner.helps.TimeUtils.TODAY_QUERY
import com.test.basd.smartjunkcleaner.helps.TimeUtils.YESTERDAY_QUERY
import com.test.basd.smartjunkcleaner.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)
        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()
    }

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


}