package com.test.basd.smartjunkcleaner.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 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.smartjunkcleaner.R
import com.test.basd.smartjunkcleaner.activity.BatteryInfoActivity
import com.test.basd.smartjunkcleaner.databinding.FragmentBatteryBinding
import com.test.basd.smartjunkcleaner.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.rgb(243, 245, 249))
        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.WHITE
        y.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART)
        y.setDrawGridLines(false)
        y.axisLineColor = Color.WHITE
        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.getData() != null &&
                binding.chart.getData().getDataSetCount() > 0
            ) {
                set1 = binding.chart.data.getDataSetByIndex(0) as LineDataSet
                set1.setValues(values)
                binding.chart.data.notifyDataChanged()
                binding.chart.notifyDataSetChanged()
            } else {
                // create a dataset and give it a type
                set1 = LineDataSet(values, "")
                set1.mode = LineDataSet.Mode.CUBIC_BEZIER
                set1.setCubicIntensity(0.2f)
                set1.setDrawFilled(true)
                set1.setDrawCircles(false)
                set1.setLineWidth(1.8f)
                set1.circleRadius = 4f
                set1.setCircleColor(Color.WHITE)
                set1.highLightColor = Color.rgb(71, 114, 255)
                set1.setColor(Color.WHITE)
                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(false)

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