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.karumi.dexter.Dexter
import com.karumi.dexter.MultiplePermissionsReport
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.PermissionRequest
import com.karumi.dexter.listener.multi.MultiplePermissionsListener
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 com.ccwangluo.accelerator.utils.SysUtils
import com.xuexiang.xutil.net.NetworkUtils
import com.xuexiang.xutil.system.PermissionUtils
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer
import java.security.Permission


class MainActivity() : XPageActivity(), TencentLocationListener {

    private val connect = registerForActivityResult(StartService()) {
        if (it) {
            ToastUtils.show("开启vpn权限失败")
        }
    }

    private lateinit var accelertorViewModel: AccelertorViewModel

    private var mSensorEventListener: SensorEventListener? = null
    private var mSensorManager: SensorManager? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        accelertorViewModel =
            ViewModelProvider(this).get(AccelertorViewModel::class.java)
        initPhoneUtils()
        //获取权限
        Dexter.withContext(this)
            .withPermissions(
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CAMERA
            )
            .withListener(object : MultiplePermissionsListener {
                override fun onPermissionsChecked(p0: MultiplePermissionsReport?) {
                    p0?.let {
                        it.grantedPermissionResponses.forEach {
                            if (it.permissionName.equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                                TencentLocationManager.getInstance(this@MainActivity)
                                    .requestSingleFreshLocation(
                                        null,
                                        this@MainActivity,
                                        Looper.getMainLooper()
                                    )
                            }
                        }
                    }
                }

                override fun onPermissionRationaleShouldBeShown(
                    p0: MutableList<PermissionRequest>?,
                    p1: PermissionToken?
                ) {
//                    PermissionUtils.openAppSettings()
                }

            }).check()
        PageOption.to(SplashFragment::class.java).open(this)

        Tencent.setIsPermissionGranted(true)
        //隐私协议
        if (!SettingSPUtils.isAgreePrivacy) {
            PrivacyDialog(this, HttpConfig.privacy_url) {
                if (it) {
                    SettingSPUtils.isAgreePrivacy = true
                } else {
                    finish()
                }

            }.show<PrivacyDialog>()
        }

        AcceleratorUtils.initConnect(this, connect)
        mSensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
        mSensorEventListener = JCVideoPlayer.JCAutoFullscreenListener()

    }

    private fun initPhoneUtils() {
        PhoneUtils.getPhoneInfo()
    }

    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
        )
        Handler().postDelayed({
            AcceleratorUtils.checkVpn()
        }, 1000)
    }

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


}