package com.lanyun.wanglaotou

import android.Manifest
import android.app.Activity
import android.app.backup.BackupManager
import android.content.Intent
import android.net.Uri
import android.net.VpnService
import android.os.Build
import android.os.Bundle
import android.os.DeadObjectException
import android.util.Log
import android.view.KeyEvent
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.view.WindowCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope

import com.google.accompanist.insets.ProvideWindowInsets
import com.lanyun.common.baseDate.themeTypeState

import com.lanyun.wanglaotou.AppConfig.ANG_PACKAGE
import com.lanyun.wanglaotou.bg.V2RayServiceManager
import com.lanyun.wanglaotou.bg.V2RayServiceManager.startV2Ray
import com.lanyun.wanglaotou.composable.MainCompose
import com.lanyun.wanglaotou.extension.toast

import com.lanyun.wanglaotou.ui.theme.CustomThemeManager
import com.lanyun.wanglaotou.util.*
import com.lanyun.wanglaotou.viewModel.MainViewModel
import com.lanyun.wanglaotou.viewModel.VpnState
import com.tbruyelle.rxpermissions.RxPermissions
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.File
import java.io.FileOutputStream
import java.util.concurrent.TimeUnit

class MainActivity : ComponentActivity(),StartCallbacks {

    private var mainViewModel = MainViewModel()
    private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) }
    private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) }
    private val requestVpnPermission = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode == RESULT_OK) {
            startV2Ray()
        }
    }
    private fun startV2Ray() {
        if (mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER).isNullOrEmpty()) {
            return
        }
        //showCircle()
//        toast(R.string.toast_services_start)
        V2RayServiceManager.startV2Ray(this)
       // hideCircle()
    }

    private fun restartV2Ray() {
        if (mainViewModel.isRunning.value == true) {
            Utils.stopVService(this)
        }
        Observable.timer(500, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                startV2Ray()
            }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        VPNManager.get().setStartCallbacks(this)

        mainViewModel.startListenBroadcast(this)
        mainViewModel.initGlobalData()
        setContent {
            val themeState = themeTypeState.value
            //设置为沉浸式状态栏
            WindowCompat.setDecorFitsSystemWindows(window, false)


            CustomThemeManager.WangLaoTouTheme(type = themeState ) {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    //可以获取状态栏高度
                    ProvideWindowInsets {

                        MainCompose(mainViewModel,onFinish = { finish() })
                    }

                }
            }
        }

        copyAssets()

        mainViewModel.toBuyUrl.observe(this, Observer {
            val intent = Intent()
            intent.action = Intent.ACTION_VIEW
            intent.data = Uri.parse(it)
            startActivity(intent)
        })


    }

    private fun copyAssets() {
        val extFolder = Utils.userAssetPath(this)
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                val geo = arrayOf("geosite.dat", "geoip.dat")
                assets.list("")
                    ?.filter { geo.contains(it) }
                    ?.filter { !File(extFolder, it).exists() }
                    ?.forEach {
                        val target = File(extFolder, it)
                        assets.open(it).use { input ->
                            FileOutputStream(target).use { output ->
                                input.copyTo(output)
                            }
                        }
                        Log.i(ANG_PACKAGE, "Copied from apk assets folder to ${target.absolutePath}")
                    }
            } catch (e: Exception) {
                Log.e(ANG_PACKAGE, "asset copy failed", e)
            }
        }
    }

    override fun onStart() {
        super.onStart()

    }

    //销毁
    override fun onDestroy() {
        super.onDestroy()
        VPNManager.get().delteCallBascks()

    }

    override fun onKeyShortcut(keyCode: Int, event: KeyEvent) = when {
        keyCode == KeyEvent.KEYCODE_G && event.hasModifiers(KeyEvent.META_CTRL_ON) -> {

            true
        }
        keyCode == KeyEvent.KEYCODE_T && event.hasModifiers(KeyEvent.META_CTRL_ON) -> {
            //stats.testConnection()
            true
        }

        else -> {
            true
        }
    }

    override fun start() {
       if (mainViewModel.isRunning.value == true){
           Utils.stopVService(this)
       } else if(settingsStorage?.decodeString(AppConfig.PREF_MODE) ?: "VPN" == "VPN") {
           val intent = VpnService.prepare(this)
           if (intent == null) {
               startV2Ray()
           } else {
               requestVpnPermission.launch(intent)
           }
       } else {
           startV2Ray()
       }
    }
   override fun stop() {
       Utils.stopVService(this)
    }

    override fun road() {
        restartV2Ray()
    }

    private fun _road() = when {

        else -> {}
    }



}