package com.test.basd.supercleanermax.fragment

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Bundle
import android.os.SystemClock
import androidx.core.content.ContextCompat
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IFillFormatter
import com.test.basd.supercleanermax.R
import com.test.basd.supercleanermax.activity.BatteryInfoActivity
import com.test.basd.supercleanermax.databinding.FragmentBatteryBinding
import com.test.basd.supercleanermax.helps.BaseFragment
import java.util.Calendar
import java.util.Date

class BatteryFragment : BaseFragment<FragmentBatteryBinding>() {
    private lateinit var batteryReceiver: BatteryReceiver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        batteryReceiver = BatteryReceiver()
    }

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

    override fun onResume() {
        super.onResume()
        val filter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        requireContext().registerReceiver(batteryReceiver, filter)
    }

    override fun onPause() {
        super.onPause()
        requireContext().unregisterReceiver(batteryReceiver)
    }

    override fun setView() {
        binding.tvGo.setOnClickListener {
            requireContext().startActivity(Intent(requireContext(), BatteryInfoActivity::class.java))
        }
//        testChart()
    }

    private inner class BatteryReceiver : BroadcastReceiver() {
        @SuppressLint("SetTextI18n")
        override fun onReceive(context: Context?, intent: Intent?) {
            val current = intent?.extras?.getInt("level") ?: 0
            val total = intent?.extras?.getInt("scale") ?: 0
            val percent = current * 100 / total
            binding.tvNumber.text = "$percent"
            when {
                percent >= 80 -> {
                    binding.ivBattery.setImageResource(R.mipmap.dianchitu_80)
                }

                percent > 50 -> {
                    binding.ivBattery.setImageResource(R.mipmap.dianchitu_50)
                }

                percent >= 30 -> {
                    binding.ivBattery.setImageResource(R.mipmap.dianchitu_30)
                }
            }

            val uptime = SystemClock.elapsedRealtime()
            val currantTime = Calendar.getInstance().time
            val batteryUseTime = currantTime.time - uptime
            val batteryDate = Date(batteryUseTime)
            binding.tvTime.text = "${batteryDate.hours} H ${batteryDate.minutes} M"
        }
    }

    fun testChart() {
        binding.chart.setViewPortOffsets(0f, 0f, 0f, 0f)
        binding.chart.setBackgroundColor(Color.parseColor("#F3F5F9"))
        binding.chart.description.isEnabled = false
        binding.chart.setDrawGridBackground(false)

        val x: XAxis = binding.chart.xAxis
        x.setDrawGridLines(false)
        x.isEnabled = false

        val y: YAxis = binding.chart.axisLeft
        y.setLabelCount(6, false)
        y.textColor = Color.TRANSPARENT
        y.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART)
        y.setDrawGridLines(false)
        y.axisLineColor = Color.TRANSPARENT
        binding.chart.axisRight.isEnabled = false


        val values = ArrayList<Entry>()

        for (i in 0 until 10) {
            val value = (Math.random() * (50 + 1)).toFloat() + 20
            values.add(Entry(i.toFloat(), value))

            var set1: LineDataSet
            if (binding.chart.data != null &&
                binding.chart.data.getDataSetCount() > 0
            ) {
                set1 = binding.chart.data.getDataSetByIndex(0) as LineDataSet
                set1.setValues(values)
                binding.chart.data.notifyDataChanged()
                binding.chart.notifyDataSetChanged()
            } else {
                set1 = LineDataSet(values, "")
                set1.mode = LineDataSet.Mode.CUBIC_BEZIER
                set1.setCubicIntensity(0.2f)
                set1.setDrawCircles(false)
                set1.setLineWidth(1.8f)
                set1.circleRadius = 4f
                set1.setDrawFilled(true)
                set1.fillDrawable = ContextCompat.getDrawable(requireContext(), R.drawable.bg_fill_drawable)
//                set1.setCircleColor(Color.parseColor("#416AFA"))
//                set1.highLightColor = Color.parseColor("#FA2F32")
//                set1.setColor(Color.parseColor("#897DFA"))
//                set1.setFillColor(Color.WHITE)
                set1.fillAlpha = 100
                set1.setDrawHorizontalHighlightIndicator(false)
                set1.fillFormatter = IFillFormatter { _, _ -> binding.chart.axisLeft.axisMinimum }

                // create a data object with the data sets
                val data = LineData(set1)
                data.setValueTextSize(9f)
                data.setDrawValues(true)

                // set data
                binding.chart.setData(data)
            }
        }
    }
}