package com.ccwangluo.accelerator.ui

import android.Manifest
import android.content.Intent
import android.hardware.Sensor
import android.os.Bundle
import android.os.Looper
import android.view.KeyEvent
import androidx.lifecycle.ViewModelProvider
import com.ccwangluo.accelerator.ui.dialog.PrivacyDialog
import com.ccwangluo.accelerator.ui.home.AccelertorViewModel
import com.ccwangluo.accelerator.ui.login.SplashFragment
import com.ccwangluo.accelerator.utils.AcceleratorUtils
import com.ccwangluo.accelerator.utils.PhoneUtils
import com.github.shadowsocks.http.HttpConfig
import com.ccwangluo.cc_quickly.utils.SettingSPUtils
import com.github.shadowsocks.bg.AuthManager
import com.github.shadowsocks.utils.StartService
import com.hjq.toast.ToastUtils
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.tauth.Tencent
import com.umeng.socialize.UMShareAPI
import com.xuexiang.xpage.base.XPageActivity
import com.xuexiang.xpage.core.PageOption
import android.hardware.SensorManager
import android.hardware.SensorEventListener
import android.os.Handler
import android.util.Log
import com.ccwangluo.accelerator.ui.dialog.PermissionDialog
import com.ccwangluo.accelerator.ui.home.AcceleratorFragment
import com.ccwangluo.accelerator.utils.datareport.DataRePortUtils
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer
import com.tencent.android.tpush.XGIOperateCallback
import com.tencent.android.tpush.XGPushManager
import com.xuexiang.xutil.system.PermissionUtils


class MainActivity() : XPageActivity(), TencentLocationListener {

    private val connect = registerForActivityResult(StartService()) {
        if (it) {
            DataRePortUtils.report("st_speed_result", mapOf("result" to 0, "cause" to 2))
            ToastUtils.show("开启vpn权限失败")
        }
    }

    private lateinit var acceleratorViewModel: AccelertorViewModel

    private var mSensorEventListener: SensorEventListener? = null
    private var mSensorManager: SensorManager? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        acceleratorViewModel =
            ViewModelProvider(this).get(AccelertorViewModel::class.java)
        // app 启动
        if (SettingSPUtils.lastAPPOpenReportTime == 0L ||
            System.currentTimeMillis() - SettingSPUtils.lastAPPOpenReportTime > 30 * 60 * 1000
        ) {
            DataRePortUtils.report("start_app")
            SettingSPUtils.lastAPPOpenReportTime = System.currentTimeMillis()
        }
        initPhoneUtils()
        PageOption.to(SplashFragment::class.java).open(this)

        Tencent.setIsPermissionGranted(true)
        //隐私协议
        if (!SettingSPUtils.isAgreePrivacy) {
            PrivacyDialog(this, HttpConfig.HTML_HOST_PRIVACY + "index.html") {
                if (it) {
                    SettingSPUtils.isAgreePrivacy = true
                    DataRePortUtils.report("st_agrmt_ok")
                    PermissionDialog(this) {
                        getPermission()
                    }.show<PermissionDialog>()
                } else {
                    finish()
                }

            }.show<PrivacyDialog>()
        } else {
            getPermission()
        }

        AcceleratorUtils.initContext(this, connect)
        mSensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
        mSensorEventListener = JCVideoPlayer.JCAutoFullscreenListener()
        DataRePortUtils.report("st_app_open")

        AcceleratorUtils.initConnect(this)

    }

    private fun getPermission() {
        PermissionUtils.permission(
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION
        ).rationale({
        }).callback(object : PermissionUtils.FullCallback {
            override fun onGranted(permissionsGranted: MutableList<String>?) {
                permissionsGranted?.forEach {
                    if (it.equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                        TencentLocationManager.getInstance(this@MainActivity)
                            .requestSingleFreshLocation(
                                null,
                                this@MainActivity,
                                Looper.getMainLooper()
                            )
                    }
                }

            }

            override fun onDenied(
                permissionsDeniedForever: MutableList<String>?,
                permissionsDenied: MutableList<String>?
            ) {

            }

        }).request()
    }

    private fun initPhoneUtils() {
        PhoneUtils.getPhoneInfo()
        //腾讯推送
        XGPushManager.registerPush(this, object : XGIOperateCallback {
            override fun onSuccess(data: Any, flag: Int) {
                //token在设备卸载重装的时候有可能会变
                Log.d("TPush", "注册成功，设备token为：$data")
                DataRePortUtils.report("st_app_start_push")
            }

            override fun onFail(data: Any, errCode: Int, msg: String) {
                Log.d("TPush", "注册失败，错误码：$errCode,错误信息：$msg")
            }
        })
    }

    override fun onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return
        }
        super.onBackPressed()
    }

    override fun onResume() {
        super.onResume()
        val mSensor = mSensorManager?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager?.registerListener(
            mSensorEventListener,
            mSensor,
            SensorManager.SENSOR_DELAY_NORMAL
        )

        AcceleratorUtils.checkVpn(this)
        //QQ官方sdk授权
        Tencent.setIsPermissionGranted(true)
    }

    override fun onPause() {
        super.onPause()
        mSensorManager?.unregisterListener(mSensorEventListener);
        JCVideoPlayer.releaseAllVideos()
    }

    override fun onStart() {
        super.onStart()
        AcceleratorUtils.onStart()
    }

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

    override fun onDestroy() {
        super.onDestroy()
        AcceleratorUtils.onDestroy(this)
    }

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        activeFragment?.let {
            if (activeFragment.onKeyDown(keyCode, event)) {
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onLocationChanged(p0: TencentLocation?, p1: Int, p2: String?) {
        if (p1 == 0) {
            p0?.province?.let {
                AuthManager.area = it
            }
        }
    }

    override fun onStatusUpdate(p0: String?, p1: Int, p2: String?) {
        println(p0)
    }


}