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.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.widget.Button
import android.widget.TextView
import android.widget.Toast
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.google.android.material.bottomnavigation.BottomNavigationView
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_main.*
import org.w3c.dom.Text
import timber.log.Timber
import com.example.watch.ui.activity.BaseData

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        initView();

        setStatusBarColor()

//        首次加载
        FirstRun()

//        登录判断
        login()

//        连接心率带
        linkHeartBand()

//        切换tab
        turnTabPage()

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

    fun setStatusBarColor() {
        val window = window
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = resources.getColor(R.color.blue)
    }


    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")
            }

//            val fragmentManager: FragmentManager = this.supportFragmentManager
//            val dialog = ScannerFragment.getInstance()
//            dialog.show(fragmentManager, "scanFragment");

//            if (isBLEEnabled()) {
//                if (!mDeviceConnected) {
//                    showDeviceScanningDialog()
//                } else {
//                    mManager!!.disConnect()
//                }
//            } else {
//                showBLEDialog()
//            }
        }
    }


    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 login() {
        val sharedPreferences = getSharedPreferences("login", 0)
        val loginState = sharedPreferences.getBoolean("token", true)
//        val loginState = true
        if (loginState) {
            sharedPreferences.edit().putBoolean("token", false).commit()
            startActivity(Intent(this, LoginActivity::class.java))
        } else {
            setContentView(R.layout.activity_main)
        }
    }

    private fun FirstRun() {
        val sharedPreferences = getSharedPreferences("FirstRun", 0)
        val first_run = sharedPreferences.getBoolean("First", true)
//        val first_run = true
        if (first_run) {
            sharedPreferences.edit().putBoolean("First", false).commit()
//            val ViewPageActivityIntent = Intent(this, ViewPageActivity::class.java)
//            startActivity(ViewPageActivityIntent)
            val OneActivityIntent = Intent(this, OneActivity::class.java)
            startActivity(OneActivityIntent)
        } else {
            setContentView(R.layout.activity_main)
        }
    }

    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 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
        )

        //心跳
        findViewById<TextView>(R.id.heartReal).text = heartRate.toString()
//        运动强度
//    男：（（-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 =锻炼持续时间的时间（以小时计）
    this.findViewById<TextView>(R.id.activLevel).text = BaseData().calcActivity(heartRate,BaseData().sex,BaseData().weight,BaseData().age,1)
//    todo 全部卡路里
//    this.findViewById<TextView>(R.id.calNum).text = ().toString()
//    todo 运动卡路里

//     todo CK

}

    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 = "--"
    }
}





