package com.ads.cal.myapplicationc

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.location.Address
import android.location.Geocoder
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.ads.cal.myapplicationc.Utils.LocationInterface
import java.util.Locale
import kotlin.math.abs

open class HomeActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val window = window
        window.statusBarColor = Color.TRANSPARENT
        window.navigationBarColor = Color.TRANSPARENT
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
        setContentView(R.layout.home_activity)
        createView()
    }

    private var magnetometer: Sensor? = null
    private var lastDegrees = 0.0
    private var currentDegrees = 0.0
    private var lastUpdateTime: Long = 0
    private var textAddress: TextView? = null
    private var sensorEventListener: SensorEventListener? = null
    private var sensorManager: SensorManager? = null
    private var accelerometer: Sensor? = null
    private var utils: Utils? = null
    private var circle_bg: ImageView? = null
    private var degrees: TextView? = null
    private var latText: TextView? = null
    private var latTextView: TextView? = null
    private var lotText: TextView? = null
    private var lotTextView: TextView? = null

    private fun createView() {
        circle_bg = findViewById(R.id.bg)
        degrees = findViewById(R.id.degrees)
        latText = findViewById(R.id.lat)
        latTextView = findViewById(R.id.lat_text)
        lotText = findViewById(R.id.lot)
        lotTextView = findViewById(R.id.lot_text)
        textAddress = findViewById(R.id.address)
        val s = findViewById<ImageView>(R.id.sss)

        s.setOnClickListener {
            val intent = Intent(this, BA::class.java)
            startActivity(intent)
        }
        createSensorMgr()
        createData()
    }

    private fun createData() {
        // 初始化LocationMgr，传递一个LocationCallback
        utils = Utils(object : LocationInterface {

            override fun locationMsgCallBack(lat: Array<String>?, log: Array<String>?) {
                if (log!!.size > 1) {
                    lotText!!.text = log[1]
                }
                if (log.isNotEmpty()) {
                    lotTextView!!.text = log[0]
                }
                if (lat!!.size > 1) {
                    latText!!.text = lat[1]
                }
                if (lat.isNotEmpty()) {
                    latTextView!!.text = lat[0]
                }
            }

            override fun locationCallBack(lat: Double, lon: Double) {
                try {
                    val address = getCityData(lat, lon)
                    textAddress!!.text =
                        String.format("%s, %s", address!!.subAdminArea, address.adminArea)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        })

        // 检查定位权限
        if (checkLocationPermission()) {
            // 如果已经有定位权限，可以开始定位
            utils!!.startTask()
        } else {
            // 如果没有定位权限，请求权限
            requestLocationPermission()
        }
    }

    private fun createSensorMgr() {
        sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
        accelerometer = sensorManager!!.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        magnetometer = sensorManager!!.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)
        // 检查传感器是否可用
        if (accelerometer != null && magnetometer != null) {
            if (null == sensorEventListener) {
                // 创建传感器监听器
                sensorEventListener = object : SensorEventListener {
                    val accelerometerData = FloatArray(3)
                    val magnetometerData = FloatArray(3)
                    override fun onSensorChanged(event: SensorEvent) {
                        if (event.sensor == accelerometer) {
                            // 平滑加速度计数据
                            for (i in event.values.indices) {
                                accelerometerData[i] =
                                    ALPHA * accelerometerData[i] + (1 - ALPHA) * event.values[i]
                            }
                        } else if (event.sensor == magnetometer) {
                            // 平滑磁力计数据
                            for (i in event.values.indices) {
                                magnetometerData[i] =
                                    ALPHA * magnetometerData[i] + (1 - ALPHA) * event.values[i]
                            }
                        }
                        // 只在两个传感器都有数据时计算方向并更新指南针
                        updateMsg(accelerometerData, magnetometerData)
                    }

                    override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
                        // 传感器精度改变时的处理
                    }
                }
            }
        } else {
            // 加速度计或磁力计不可用，进行错误处理
        }
    }

    private fun updateMsg(accelerometerData: FloatArray, magnetometerData: FloatArray) {
        // 计算方向并更新指南针
        val rotationMatrix = FloatArray(9)
        val orientationValues = FloatArray(3)
        val success = SensorManager.getRotationMatrix(
            rotationMatrix,
            null,
            accelerometerData,
            magnetometerData
        )
        if (success) {
            SensorManager.getOrientation(rotationMatrix, orientationValues)
            // 获取当前时间
            val currentTime = System.currentTimeMillis()
            // 更新指南针或其他UI元素
            currentDegrees = Math.toDegrees(orientationValues[0].toDouble())
            if (abs(currentDegrees - lastDegrees) >= 1 && currentTime - lastUpdateTime >= 20) {
                runOnUiThread(task)
                lastUpdateTime = currentTime
                // 更新上次更新时间
            }
        }
    }

    private val task = Runnable { rotate(currentDegrees) }
    private fun rotate(currentDegrees: Double) {
        val rotation = (currentDegrees + 360) % 360
        circle_bg!!.rotation = -rotation.toFloat()
        lastDegrees = currentDegrees
        degrees!!.text = String.format("%s%s", directionFromAngle, rotation.toInt())
    }

    override fun onResume() {
        super.onResume()
        // 注册传感器监听器
        if (null != accelerometer) {
            sensorManager!!.registerListener(
                sensorEventListener,
                accelerometer,
                SensorManager.SENSOR_DELAY_GAME
            )
        }
        if (null != magnetometer) {
            sensorManager!!.registerListener(
                sensorEventListener,
                magnetometer,
                SensorManager.SENSOR_DELAY_GAME
            )
        }
    }

    override fun onPause() {
        super.onPause()
        if (null != sensorEventListener) {
            if (null != sensorManager) {
                sensorManager!!.unregisterListener(sensorEventListener)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (null != sensorEventListener) {
            if (null != sensorManager) {
                sensorManager!!.unregisterListener(sensorEventListener)
                sensorEventListener = null
            }
        }
    }

    private fun checkLocationPermission(): Boolean {
        // 检查是否有定位权限
        return (ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED)
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == LOCATION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了定位权限，现在可以开始定位
                utils!!.startTask()
            } else {
                // 用户拒绝了定位权限
            }
        }
    }

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

    // 将角度规范化到0到360度之间
    private val directionFromAngle: String
        // 定义方向的范围
        get() {
            val angle = ((lastDegrees % 360 + 360) % 360).toFloat()
            return if (angle >= 68 && angle < 113) {
                getString(R.string.a)
            } else if (angle >= 23 && angle < 68) {
                getString(R.string.b)
            } else if (angle >= 113 && angle < 157) {
                getString(R.string.c)
            } else if (angle >= 157 && angle < 203) {
                getString(R.string.d)
            } else if (angle >= 203 && angle < 248) {
                getString(R.string.e)
            } else if (angle >= 248 && angle < 293) {
                getString(R.string.f)
            } else if (angle >= 293 && angle < 338) {
                getString(R.string.g)
            } else {
                getString(R.string.h)
            }
        }

    private fun requestLocationPermission() {
        // 请求定位权限
        ActivityCompat.requestPermissions(
            this,
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ),
            LOCATION_REQUEST_CODE
        )
    }

    companion object {
        private const val LOCATION_REQUEST_CODE = 7 // 自定义的请求码
        private const val ALPHA = 0.85f // 调整这个值以控制平滑程度
        fun getCityData(la: Double, lo: Double): Address? {
            var result: Address? = null
            try {
                val gc = BaseApplication.context?.let { Geocoder(it, Locale.getDefault()) }
                val data = gc?.getFromLocation(
                    la,
                    lo, 1
                )
                if (null != data && data.size > 0) {
                    result = data[0]
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return result
        }
    }
}