package com.ccwangluo.accelerator.ui

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import com.ccwangluo.accelerator.ui.view.PrivacyDialog
import com.ccwangluo.accelerator.utils.LoginUtils
import com.ccwangluo.accelerator.utils.PhoneUtils
import com.ccwangluo.accelerator.utils.http.HttpConfig
import com.ccwangluo.cc_quickly.utils.SettingSPUtils
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.mmkv.MMKV
import com.tencent.tauth.Tencent
import com.umeng.socialize.UMShareAPI
import com.xuexiang.xpage.base.XPageActivity
import com.xuexiang.xpage.core.PageOption


class MainActivity() : XPageActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        MMKV.initialize(this)
        initPhoneUtils()
        //获取权限
        Dexter.withContext(this)
            .withPermissions(
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
            .withListener(object : MultiplePermissionsListener {
                override fun onPermissionsChecked(p0: MultiplePermissionsReport?) {
                    println(p0)
                }

                override fun onPermissionRationaleShouldBeShown(
                    p0: MutableList<PermissionRequest>?,
                    p1: PermissionToken?
                ) {
                    println(p0)
                    println(p1)
                }

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

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

            }).show<PrivacyDialog>()
        }
    }

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

    override fun onDestroy() {
        super.onDestroy()
        LoginUtils.clearToken()
    }

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


}