package com.cr.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.util.AttributeSet
import com.cr.common.CrColorManager
import com.cr.common.CrUnitManager
import com.cr.cruav.R

/**
 * 操作系统：MAC系统
 * 创建者：王成
 * 创建日期：2023/8/1 09:33
 * 描述：指南针组件
 */
class CrCompassWidget @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAtr: Int = 0
) : CrBaseDrawWidget(context, attrs, defStyleAtr), SensorEventListener {
    // todo: 2023/8/1 画笔定义
    private var mLinePaint: Paint? = null  // define: 2023/8/1 线画笔
    private var mCirclePaint: Paint? = null // define: 2023/8/1 圆画笔
    private var mCircleCenterPaint: Paint? = null  // define: 2023/8/1 圆心画笔
    private var mArcScanPaint: Paint? = null // define: 2023/8/1 扫描圆弧画笔

    // todo: 2023/8/1 宽度定义
    private var mStrokeWith: Int = 1  // define: 2023/8/1 描边宽度
    private var mScanAngle: Float = 90f // define: 2023/8/1 扫描角度

    // todo: 2023/8/1 传感器
    private var sensorManger: SensorManager? = null // define: 2023/8/1 传感器管理器
    private var magneticSensor: Sensor? = null  // define: 2023/8/1 磁场传感器
    private var accelerometerSensor: Sensor? = null  // define: 2023/8/1 加速度传感器
    private var values: FloatArray = FloatArray(3) // define: 2023/8/1 计算值
    private var r: FloatArray = FloatArray(9)  // define: 2023/8/1 旋转矩阵
    private var gravity: FloatArray = FloatArray(3)  // define: 2023/8/1 磁场传感器数据
    private var geomagnetic: FloatArray = FloatArray(3)  // define: 2023/8/1 加速度传感器数据

    /**
     * 初始还
     */
    init {
        // todo: 2023/8/1 初始化画笔
        initPaint()
    }

    /**
     * 初始化传感器
     */
    private fun initSensor(){
        // todo: 2023/8/1 初始化传感器
        sensorManger = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        sensorManger?.let { itSensorManager ->
            // todo: 2023/8/15 检测传感器是否存在
            if(itSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) == null ||
                itSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) == null){
                return
            }
            // todo: 2023/8/1 获取传感器
            magneticSensor = itSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)
            accelerometerSensor = itSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)

            // todo: 2023/8/2 SensorManager.SENSOR_DELAY_GAME 代表更新速率 指最高的速率

            // todo: 2023/8/1 注册地磁传感器事件
            magneticSensor?.let {
                itSensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_GAME)
            }

            // todo: 2023/8/1 注册加速度传感器事件
            accelerometerSensor?.let {
                itSensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_GAME)
            }
        }
    }

    /**
     * 加入窗体
     */
    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        initSensor()
    }

    /**
     * 移除窗体
     */
    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        // todo: 2023/8/1 移除注册的监听事件
        sensorManger?.let {
            it.unregisterListener(this)
        }
        sensorManger = null
    }

    /**
     * 绘制
     * @param canvas Canvas
     */
    override fun draw(canvas: Canvas?) {
        // todo: 2023/8/1 继承超类的方法 即可获取全局画布
        super.draw(canvas)
        // todo: 2023/8/1 绘制线
        drawLine()
        // todo: 2023/8/1 绘制圆
        drawCircle()
        // todo: 2023/8/1 绘制扫描圆弧
        drawScanArc()
        // todo: 2023/8/1 绘制圆心
        drawCircleCenter()
    }

    /**
     * 绘制扫描圆弧
     */
    private fun drawScanArc() {
        var paddingPixel: Float = CrUnitManager.dp2px(2f)
        // todo: 2023/8/1 圆弧绘制区域
        var mRectF: RectF = RectF(
            paddingPixel,
            paddingPixel,
            canvasSize - paddingPixel,
            canvasSize - paddingPixel
        )
        mArcScanPaint?.alpha = 80
        canvas?.drawArc(mRectF, mScanAngle - 15, 30f, true, mArcScanPaint!!)
    }

    /**
     * 绘制圆心
     */
    private fun drawCircleCenter() {
        var centerX: Float = canvasSize / 2f
        var centerY: Float = canvasSize / 2f
        var radius: Float = CrUnitManager.dp2px(3f)
        canvas?.drawCircle(centerX, centerY, radius, mCircleCenterPaint!!)
    }

    /**
     * 绘制线
     */
    private fun drawLine() {
        // todo: 2023/8/1 画横线
        var hStartX: Float = 0f
        var hStartY: Float = canvasSize / 2f
        var hEndX: Float = canvasSize * 1f
        var hEndY: Float = canvasSize / 2f
        canvas?.drawLine(hStartX, hStartY, hEndX, hEndY, mLinePaint!!)

        // todo: 2023/8/1 画竖线
        var vStartX: Float = canvasSize / 2f
        var vStartY: Float = 0f
        var vEndX: Float = canvasSize / 2f
        var vEndY: Float = canvasSize * 1f
        canvas?.drawLine(vStartX, vStartY, vEndX, vEndY, mLinePaint!!)
    }

    /**
     * 绘制圆
     */
    private fun drawCircle() {
        var radius: Float = (canvasSize / 2f - 20) / 5f
        var centerX: Float = canvasSize / 2f
        var centerY: Float = canvasSize / 2f
        for (index in 1 until 6) {
            mCirclePaint?.alpha = 255 - ((255 - 30) / 5) * index
            canvas?.drawCircle(centerX, centerY, radius * index, mCirclePaint!!)
        }
    }

    /**
     * 初始化画笔
     */
    private fun initPaint() {
        // todo: 2023/8/1 初始化线画笔
        mLinePaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mLinePaint?.let {
            crPaintInit(it)
            it.strokeWidth = CrUnitManager.dp2px(mStrokeWith).toFloat()
        }
        // todo: 2023/8/1 初始化圆画笔
        mCirclePaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mCirclePaint?.let {
            crPaintInit(it)
            it.strokeWidth = CrUnitManager.dp2px(mStrokeWith).toFloat()
        }
        // todo: 2023/8/1 初始化圆心画笔
        mCircleCenterPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mCircleCenterPaint?.let {
            crPaintInit(it)
            it.style = Paint.Style.FILL
            it.color = CrColorManager.getColor(context, R.color.white)
            it.alpha = 255
            it.strokeWidth = CrUnitManager.dp2px(3f)
        }
        // todo: 2023/8/1 扫描圆弧画笔
        mArcScanPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mArcScanPaint?.let {
            crPaintInit(it)
            it.alpha = 80
            it.color = CrColorManager.getColor(context, R.color.palegreen)
            it.style = Paint.Style.FILL
        }
    }

    /**
     * 传感器变化监听
     * @param event SensorEvent
     */
    override fun onSensorChanged(event: SensorEvent?) {
        // todo: 2023/8/2 地磁传感器
        if (event?.sensor?.type == Sensor.TYPE_MAGNETIC_FIELD) {
            geomagnetic = event?.values
        }
        // todo: 2023/8/2 加速度传感器
        if (event?.sensor?.type == Sensor.TYPE_ACCELEROMETER) {
            gravity = event?.values
            getValue()
        }
    }

    /**
     * 精度变化监听
     * @param p0 Sensor
     * @param p1 Int
     */
    override fun onAccuracyChanged(p0: Sensor?, p1: Int) {

    }

    /**
     * 获取值
     */
    private fun getValue() {
        // todo: 2023/8/1 传入地磁数据和加速度数据 计算旋转矩阵r
        SensorManager.getRotationMatrix(r, null, gravity, geomagnetic)
        // todo: 2023/8/1 根据旋转矩阵r计算方向数据
        // todo: 2023/8/1 values[0] 记录手机绕 Z 轴旋转角度
        // todo: 2023/8/1 values[1] 记录手机绕 X 轴旋转角度
        // todo: 2023/8/1 values[2] 记录手机绕 Y 轴旋转角度
        SensorManager.getOrientation(r, values)
        var z: Double = Math.toDegrees(values!![0].toDouble()) - 90
        var x: Double = Math.toDegrees(values!![1].toDouble())
        var y: Double = Math.toDegrees(values!![2].toDouble())
//        CrUtil.print(String.format("方位角:%.2f x方向:%.2f y方向:%.2f", z, x, y))
        mScanAngle = z.toFloat()
        invalidate()
    }
}