package com.example.watch.ui.activity

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.provider.Settings.SettingNotFoundException
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.android.chileaf.WearManager
import com.android.chileaf.fitness.callback.WearManagerCallbacks
import com.example.watch.BuildConfig
import com.example.watch.R
import com.github.aachartmodel.aainfographics.aachartcreator.AAChartModel
import com.github.aachartmodel.aainfographics.aachartcreator.AAChartType
import com.github.aachartmodel.aainfographics.aachartcreator.AAChartView
import com.github.aachartmodel.aainfographics.aachartcreator.AASeriesElement
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_main.*
import timber.log.Timber
import java.util.*
import kotlin.concurrent.fixedRateTimer


class MainActivity : AppCompatActivity(), ScannerFragment.OnDeviceSelectedListener,
    WearManagerCallbacks {
    private var mDeviceConnected = false
    private val mTvAppVersion: TextView? = null
    private val mTvDeviceName: TextView? = null
    private val mTvVersion: TextView? = null
    private val mTvRssi: TextView? = null
    private val mTvBattery: TextView? = null
    private val mTvSport: TextView? = null
    private val mTvHeartRate: TextView? = null
    private val mBtnConnect: Button? = null

    private val viewPager: ViewPager? = null
    private val bottomNavigationView: BottomNavigationView? = null
    private val mPagerAdapter: FragmentPagerAdapter? = null

    var toast: Toast? = null
    var mExitTime: Long = 0
    var HeartLine = arrayListOf<Any>(0, 0, 0)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

//        首次加载
        FirstRun()

        initView();

//        连接心率带
        linkHeartBand()

//        切换tab
        turnTabPage()

//        填写基础身体数据
        setDeafultData()

//        开始运动
        beginSport()

//        绘制心律图
        ChartView()
//        心跳动画
        heartAnimate()

    }

    fun heartAnimate(){
        val mIdIvFace = findViewById<ImageView>(R.id.heart)


        // 设置移动效果
        /**
         *
         * float fromXDelta 动画开始的点离当前View X坐标上的差值
         * float toXDelta 动画结束的点离当前View X坐标上的差值
         * float fromYDelta 动画开始的点离当前View Y坐标上的差值
         * float toYDelta 动画开始的点离当前View Y坐标上的差值
         */


        // 设置移动效果
        /**
         *
         * float fromXDelta 动画开始的点离当前View X坐标上的差值
         * float toXDelta 动画结束的点离当前View X坐标上的差值
         * float fromYDelta 动画开始的点离当前View Y坐标上的差值
         * float toYDelta 动画开始的点离当前View Y坐标上的差值
         */
        val translateAnimation: Animation = TranslateAnimation(0F, 20F, 0F, 20F)
        // 设置动画持续时间
        // 设置动画持续时间
        translateAnimation.duration = 30000
        // 为ImageView设置动画效果
        // 为ImageView设置动画效果
        mIdIvFace.setAnimation(translateAnimation)
        // 启动动画
        // 启动动画
        translateAnimation.startNow()
    }

    fun setStatusBarColor(colorType: String) {
        val window = window
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        when (colorType) {
            in "blue" -> window.statusBarColor = resources.getColor(R.color.blue)
            in "violate" -> window.statusBarColor = resources.getColor(R.color.violate)
            in "greendeep" -> window.statusBarColor = resources.getColor(R.color.greendeep)
            in "yellowdeep" -> window.statusBarColor = resources.getColor(R.color.yellowdeep)
            in "orange" -> window.statusBarColor = resources.getColor(R.color.orange)
            in "reddeep" -> window.statusBarColor = resources.getColor(R.color.reddeep)
        }
    }


    private fun linkHeartBand() {
        val chainBtn = findViewById<Button>(R.id.chainBtn)
        chainBtn.setOnClickListener {
            val dialog = ScannerFragment.getInstance()
            if (dialog == null) {
                println("1122")
            } else {
                dialog.show(supportFragmentManager, "scan_fragment")
            }
        }
    }


    private fun turnTabPage() {
        val home_btn = findViewById<View>(R.id.navigation_home)
        home_btn.setOnClickListener {
            startActivity(Intent(this, MainActivity::class.java))
        }
        val setting_btn = findViewById<View>(R.id.navigation_setting)
        setting_btn.setOnClickListener {
            val SettingActivityIntent = Intent(this, SettingActivity::class.java)
            startActivity(SettingActivityIntent)
        }
    }

    private fun initView() {

        mManager = WearManager.getInstance(this)
        mManager!!.setDebug(BuildConfig.DEBUG)
        mManager!!.setManagerCallbacks(this)
    }

    private fun FirstRun() {
        val sharedPreferences = getSharedPreferences("FirstRun", 0)
        val first_run = sharedPreferences.getBoolean("First", true)
        if (first_run) {
            sharedPreferences.edit().putBoolean("First", false).apply()
            val OneActivityIntent = Intent(this, OneActivity::class.java)
            startActivity(OneActivityIntent)
        } else {
            login()
        }
    }

    private fun login() {
        val sharedPreferences = getSharedPreferences("login", 0)
        val loginState = sharedPreferences.getBoolean("token", true)
        if (loginState) {
            sharedPreferences.edit().putBoolean("token", false).apply()
            startActivity(Intent(this, LoginActivity::class.java))
        } else {
            setContentView(R.layout.activity_main)
            setStatusBarColor("blue")
        }
    }


    protected var mManager: WearManager? = null
    protected var mLoading: LoadingDialog? = null
    protected var mHandler = Handler(Looper.getMainLooper())

    private fun showLoading() {
        showLoading(getString(R.string.loading))
    }


    private fun showLoading(message: String?) {
        mLoading = LoadingDialog.Builder(this)
            .setMessage(message)
            .build()
        mLoading!!.show()
    }

    private fun showLoadingAutoDismiss(delay: Long) {
        showLoading()
        mHandler.postDelayed(Runnable { hideLoading() }, delay)
    }

    private fun hideLoading() {
        if (mLoading != null && mLoading!!.isShowing()) {
            mLoading!!.dismiss()
        }
    }

    private fun showToast(message: String?) {
        runOnUiThread { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() }
    }

    private fun ensureBLESupported() {
        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, R.string.no_ble, Toast.LENGTH_LONG).show()
            finish()
        }
    }

    private fun isBLEEnabled(): Boolean {
        val bluetoothManager = getSystemService(BLUETOOTH_SERVICE) as BluetoothManager
        val adapter = bluetoothManager.adapter
        return adapter != null && adapter.isEnabled
    }

    private fun showBLEDialog() {
        val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        startActivity(enableIntent)
    }


    //Scan device
    private fun showDeviceScanningDialog() {
        if (isLocationEnabled(this)) {
            AndPermission.with(this)
                .runtime()
                .permission(
                    Permission.ACCESS_FINE_LOCATION,
                    Permission.ACCESS_COARSE_LOCATION,
                    Permission.ACCESS_BACKGROUND_LOCATION
                )
                .onGranted { permissions ->
                    runOnUiThread {
                        val dialog: ScannerFragment = ScannerFragment.getInstance()
                        dialog.show(supportFragmentManager, "scan_fragment")
                    }
                }
                .onDenied({ permissions ->
                    if (AndPermission.hasAlwaysDeniedPermission(this@MainActivity, permissions)) {
                        AlertDialog.Builder(this)
                            .setTitle(getString(R.string.permission_required))
                            .setMessage(getString(R.string.permission_location_info))
                            .setPositiveButton("OK") { dialog: DialogInterface?, which: Int -> onPermissionSettings() }
                            .setNegativeButton("Cancel", null)
                            .show()
                    }
                })
                .start()
        } else {
            AlertDialog.Builder(this)
                .setTitle(getString(R.string.location_permission_title))
                .setMessage(getString(R.string.location_permission_info))
                .setPositiveButton("OK") { dialog: DialogInterface?, which: Int -> onEnableLocation() }
                .setNegativeButton("Cancel", null)
                .show()
        }
    }

    fun isLocationEnabled(context: Context): Boolean {
        var locationMode = Settings.Secure.LOCATION_MODE_OFF
        try {
            locationMode = Settings.Secure.getInt(
                context.contentResolver,
                Settings.Secure.LOCATION_MODE
            )
        } catch (e: SettingNotFoundException) {
            // do nothing
        }
        return locationMode != Settings.Secure.LOCATION_MODE_OFF
        return true
    }

    fun onEnableLocation() {
        val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
        startActivity(intent)
    }

    fun onPermissionSettings() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.fromParts("package", packageName, null)
        startActivity(intent)
    }

    private fun defaultUI() {
        mTvDeviceName?.setText("Device name")
        mTvVersion?.setText("Version:--")
        mTvRssi?.setText("Rssi:--")
        mTvBattery?.setText("Battery:--")
        mTvSport?.setText("Sport:--")
        mTvHeartRate?.setText("Heart Rate:--")
        mBtnConnect?.setText(getString(R.string.action_connect))
    }


    private fun getVersionName(): String? {
        try {
            val packageInfo = packageManager.getPackageInfo(packageName, 0)
            return packageInfo.versionName
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    override fun onDeviceSelected(device: BluetoothDevice?, name: String?) {
        mManager!!.connect(device, false)
//        mTvDeviceName!!.text = getString(R.string.device_name, name)
    }

    override fun onDeviceConnected(device: BluetoothDevice) {
        mDeviceConnected = true
//        runOnUiThread { mBtnConnect!!.setText(R.string.action_disconnect) }
    }

    override fun onDeviceDisconnected(device: BluetoothDevice) {
        runOnUiThread { defaultUI() }
        mDeviceConnected = false
        mManager!!.close()
    }


    override fun onError(device: BluetoothDevice, message: String, errorCode: Int) {
        Timber.e("onError: ($errorCode)")
        showToast("$message ($errorCode)")
    }

    override fun onDeviceNotSupported(device: BluetoothDevice) {
        showToast(getString(R.string.not_supported))
    }

    override fun onSoftwareVersion(device: BluetoothDevice, software: String) {
        runOnUiThread { mTvVersion?.setText("Version:$software") }
    }

    override fun onRssiRead(device: BluetoothDevice, rssi: Int) {
        runOnUiThread { mTvRssi?.setText("Rssi:" + rssi + "dBm") }
    }

    override fun onBatteryLevelChanged(device: BluetoothDevice, batteryLevel: Int) {
        findViewById<TextView>(R.id.head_status).text =
            "心率带已连接 电量" + getString(R.string.battery, batteryLevel)
    }

    //   卡路里和全部卡路里以及CK
    override fun onSportReceived(device: BluetoothDevice, step: Int, distance: Int, calorie: Int) {
        findViewById<TextView>(R.id.sportNum).text = calorie.toString()
        findViewById<TextView>(R.id.calNum).text = (calorie * 1.25).toInt().toString()
        findViewById<TextView>(R.id.ckNum).text = BaseData().calcCk(calorie)

    }

    //    连续两次回退
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis().minus(mExitTime) <= 3000) {
                finish()
            } else {
                mExitTime = System.currentTimeMillis()
                showToast("再按一次退出程序")
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    //    获取心率数据
    override fun onHeartRateMeasurementReceived(
        device: BluetoothDevice,
        heartRate: Int,
        contactDetected: Boolean?,
        energyExpanded: Int?,
        rrIntervals: MutableList<Int>?
    ) {
        super.onHeartRateMeasurementReceived(
            device,
            heartRate,
            contactDetected,
            energyExpanded,
            rrIntervals
        )
//        心率带已链接
        bindHeartSuccess()

        //心跳
        findViewById<TextView>(R.id.heartReal).text = heartRate.toString()
        if (rrIntervals != null) {
            findViewById<TextView>(R.id.rrIntervals).text = rrIntervals.toString()
        }
//        把心跳数塞进去
        val aaChartView = findViewById<AAChartView>(R.id.aa_chart_view)
        if(HeartLine.size > 10){
            HeartLine.remove(0)
        }
        HeartLine.add(heartRate)
        aaChartView.aa_onlyRefreshTheChartDataWithChartOptionsSeriesArray(
            arrayOf(
                AASeriesElement()
                    .name("心率趋势图")
                    .data(
                        HeartLine.toArray()
                    )
            )
        )

//        todo 最大心率 和 平均心率
//        val arrayList = ArrayList<Int>()



//        运动强度
//    男：（（-55.0969 +（0.6309×HR）+（0.1988 xW）+（0.2017×A））/ 4.184）×60 xT
//    女：（（-20.4022 +（0.4472×HR） - （0.1263 xW）+（0.074×A））/ 4.184）×60 xT
//    其中，HR =心率（次/分钟） W =体重（公斤） A=年龄（岁） T =锻炼持续时间的时间（以小时计）
        var ActityVal =
            BaseData().calcActivity(heartRate, BaseData().sex, BaseData().weight, BaseData().age, 1)
        this.findViewById<TextView>(R.id.activLevel).text = ActityVal


//        根据运动强度加载不同的背景色，状态栏颜色 和 提示语
        headStatus(ActityVal.toInt())
    }

    fun setDeafultData() {
        this.findViewById<TextView>(R.id.height).text = BaseData().heigh.toString()
//        var sex = if (BaseData().sex == 1) "男" else "女"
//        this.findViewById<TextView>(R.id.sex).text = sex
        this.findViewById<TextView>(R.id.age).text = BaseData().age.toString()
        this.findViewById<TextView>(R.id.weight).text = BaseData().weight.toString()
        this.findViewById<TextView>(R.id.peaceHr).text = BaseData().peaceHr.toString()

        this.findViewById<TextView>(R.id.activLevel).text = "--"
        this.findViewById<TextView>(R.id.heartReal).text = "--"
    }

    //    心率带已链接
    fun bindHeartSuccess() {
        findViewById<ImageView>(R.id.chain).setVisibility(View.GONE); // 隐藏
        findViewById<Button>(R.id.chainBtn).setVisibility(View.GONE); // 隐藏
        findViewById<TextView>(R.id.unchain).text = "心率带已连接"
        findViewById<TextView>(R.id.unchain).setTextColor(Color.parseColor("#AACC03"))
    }

    //    开始运动
    fun beginSport() {
//        开始
        val beginBtn = findViewById<Button>(R.id.beginBtn)
        beginBtn.setOnClickListener {
            showToast("运动计时已开")
            timeInter()
        }

        val reportHr = findViewById<Button>(R.id.reportHr)
        reportHr.setOnClickListener {
            showToast("心率已上报 todo")
        }
    }

    fun timeInter() {
        lateinit var timer: Timer
        var milliseconds: Long = 1000
        timer = fixedRateTimer("", false, 0, 1000) {
            val hours = milliseconds % 1000
            val minutes = milliseconds / 1000 / 60
            val seconds = milliseconds / 1000 % 60
            val showHours = if (hours > 9) hours else "0" + hours;
            val showminutes = if (minutes > 9) minutes else "0" + minutes;
            val showseconds = if (seconds > 9) seconds else "0" + seconds;
            val task = "运动时长" + showHours + ":" + showminutes + ":" + showseconds
            findViewById<Button>(R.id.beginBtn).text = task
            milliseconds = milliseconds + 1000
        }

        //          结束
        val btn_stop = findViewById<Button>(R.id.btn_stop)
        btn_stop.setOnClickListener {
            showToast("运动计时已终止")
            findViewById<Button>(R.id.beginBtn).text = "开始运动"
            timer.cancel()
        }
    }

    fun headStatus(activLevel: Int) {
        val activLevelVal = findViewById<TextView>(R.id.act_level_text)
        var levelText = "激活放松"
        when (activLevel) {
            in 0..39 -> levelText = "激活放松"
            in 40..54 -> levelText = "动态热身"
            in 55..69 -> levelText = "脂肪燃烧"
            in 70..79 -> levelText = "糖分消耗"
            in 80..89 -> levelText = "心肺训练"
            in 90..109 -> levelText = "峰值锻炼"
        }
        activLevelVal.text = levelText
        val headBg = findViewById<LinearLayout>(R.id.head_bg)
        when (activLevel) {
            in 0..39 -> headBg.setBackgroundColor(Color.parseColor("#028FE1"))
            in 40..54 -> headBg.setBackgroundColor(Color.parseColor("#6D29FA"))
            in 55..69 -> headBg.setBackgroundColor(Color.parseColor("#0AB105"))
            in 70..79 -> headBg.setBackgroundColor(Color.parseColor("#B9CB01"))
            in 80..89 -> headBg.setBackgroundColor(Color.parseColor("#EA8813"))
            in 90..109 -> headBg.setBackgroundColor(Color.parseColor("#D11122"))
        }
        when (activLevel) {
            in 0..39 -> setStatusBarColor("blue")
            in 40..54 -> setStatusBarColor("violate")
            in 55..69 -> setStatusBarColor("greendeep")
            in 70..79 -> setStatusBarColor("yellowdeep")
            in 80..89 -> setStatusBarColor("orange")
            in 90..109 -> setStatusBarColor("reddeep")
        }
    }

    fun ChartView() {
        val aaChartView = findViewById<AAChartView>(R.id.aa_chart_view)
//        arrayOf(0, 0)
        val aaChartModel = AAChartModel()
            .chartType(AAChartType.Line)
            .backgroundColor("#fff")
            .series(
                arrayOf(
                    AASeriesElement()
                        .name("心率趋势图")
                        .data(HeartLine.toArray())
                )
            )
        /*图表视图对象调用图表模型对象,绘制最终图形*/
        aaChartView.aa_drawChartWithChartModel(aaChartModel)
    }
}






