package com.ccwangluo.accelerator.ui

import android.Manifest
import android.app.DownloadManager
import android.content.Intent
import android.content.IntentFilter
import android.hardware.Sensor
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import androidx.lifecycle.ViewModelProvider
import com.ccwangluo.accelerator.receiver.AppDownloadReceiver
import com.ccwangluo.accelerator.ui.dialog.PermissionDialog
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.manager.PhoneUtils
import com.ccwangluo.accelerator.utils.datareport.DataRePortUtils
import com.ccwangluo.cc_quickly.utils.SettingSPUtils
import com.github.shadowsocks.http.HttpConfig
import com.github.shadowsocks.utils.StartService
import com.hjq.toast.ToastUtils
import com.tencent.android.tpush.XGIOperateCallback
import com.tencent.android.tpush.XGPushManager
import com.tencent.bugly.Bugly
import com.tencent.tauth.Tencent
import com.umeng.commonsdk.UMConfigure
import com.umeng.socialize.UMShareAPI
import com.xuexiang.xpage.base.XPageActivity
import com.xuexiang.xpage.core.PageOption
import com.xuexiang.xutil.system.PermissionUtils
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer


class MainActivity() : XPageActivity() {

    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
    private val appDownReceiver = AppDownloadReceiver()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        acceleratorViewModel =
            ViewModelProvider(this).get(AccelertorViewModel::class.java)

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

            }.show<PrivacyDialog>()
        } else {
            PhoneUtils.initSdk(application)
            PhoneUtils.getPhoneInfo()
            getPermission()
        }

        AcceleratorUtils.initContext(this, connect)
        mSensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
        mSensorEventListener = JCVideoPlayer.JCAutoFullscreenListener()
        AcceleratorUtils.initConnect(this)
        registerReceiver(appDownReceiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
    }

    private fun getPermission() {
        initPhoneUtils()
        Bugly.init(this, "e030f74df5", false)
        UMConfigure.init(this,"61f0aa7fe014255fcb06a0bd"
            ,"umeng", UMConfigure.DEVICE_TYPE_PHONE,"")
        PageOption.to(SplashFragment::class.java).open(this)
        //QQ官方sdk授权
        Tencent.setIsPermissionGranted(true)
        // app 启动
        if (SettingSPUtils.lastAPPOpenReportTime == 0L ||
            System.currentTimeMillis() - SettingSPUtils.lastAPPOpenReportTime > 30 * 60 * 1000
        ) {
            DataRePortUtils.report("start_app")
            SettingSPUtils.lastAPPOpenReportTime = System.currentTimeMillis()
        }
        PermissionUtils.permission(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
        ).rationale({
        }).callback(object : PermissionUtils.FullCallback {
            override fun onGranted(permissionsGranted: MutableList<String>?) {

            }

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

            }

        }).request()

    }

    private fun initPhoneUtils() {
        //腾讯推送
        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)

    }

    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()
        unregisterReceiver(appDownReceiver)
        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)
    }


}