package com.duolebo.blyrobot

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.*
import com.duolebo.blyrobot.activity.PackageListActivity
import com.duolebo.blyrobot.data.ApkPackageInfo
import com.duolebo.blyrobot.service.BylRobotService
import com.duolebo.blyrobot.service.BylWebService
import com.duolebo.blyrobot.util.AppUtil
import com.duolebo.blyrobot.util.Constants
import com.minhui.vpn.ProxyConfig
import com.minhui.vpn.VPNConstants.*
import com.minhui.vpn.utils.ThreadProxy
import com.minhui.vpn.utils.VpnServiceHelper
import com.minhui.vpn.utils.VpnServiceHelper.START_VPN_SERVICE_REQUEST_CODE
import java.io.File
import java.io.FileFilter

class CaptureActivity : AppCompatActivity() {

    private val REQUEST_PACKAGE = 103
    private lateinit var captureButton:Button

    private var vpnStatusListener: ProxyConfig.VpnStatusListener = object : ProxyConfig.VpnStatusListener {

        override fun onVpnStart(context: Context) {
            runOnUiThread {
                refreshCaptureBtn()
            }
        }

        override fun onVpnEnd(context: Context) {
            runOnUiThread {
                refreshCaptureBtn()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.i("", "onCreate....")
        setContentView(R.layout.activity_capture)
        ProxyConfig.Instance.registerVpnStatusListener(vpnStatusListener)
//        startService(Intent(this, BylRobotService::class.java))
        val selectBtn = findViewById<Button>(R.id.selectBtn)
        selectBtn.setOnClickListener{
            selectApp()
        }

        captureButton = findViewById(R.id.captureBtn)
        captureButton.setOnClickListener {
            runOrStopCapture()
        }

        val clearBtn = findViewById<Button>(R.id.clearBtn)
        clearBtn.setOnClickListener {
            clearHistoryData()
        }

        initCheckbox()

        val webUrlText = findViewById<TextView>(R.id.webUrl)
        webUrlText.text = "启动抓取后请在浏览器打开：\nhttp://" + AppUtil.getIPAddress(true, null) + ":48080"

        startRobotService()
    }

    private fun startRobotService() {
        startService(Intent(this, BylRobotService::class.java))
    }

    private fun initCheckbox() {
        val checkbox = findViewById<CheckBox>(R.id.videoCheckbox)
        val sp = getSharedPreferences(VPN_SP_NAME, Context.MODE_PRIVATE)
        checkbox.isChecked = sp.getBoolean(Constants.ONLY_VIDEO, false)
        checkbox.setOnCheckedChangeListener { _, isChecked ->
            sp.edit().putBoolean(Constants.ONLY_VIDEO, isChecked).apply()
        }
    }

    override fun onResume() {
        super.onResume()
        refreshCaptureBtn()
    }

    override fun onDestroy() {
        super.onDestroy()
        ProxyConfig.Instance.unregisterVpnStatusListener(vpnStatusListener)
    }

    private fun refreshCaptureBtn() {
        if (VpnServiceHelper.vpnRunningStatus()) {
            captureButton.text = "停止抓取"
        }
        else {
            captureButton.text = "启动抓取"
        }
    }

    private fun runOrStopCapture() {
        if (VpnServiceHelper.vpnRunningStatus()) {
            // 由于5.0以下系统无法控制抓取规则，所以停止抓取之后才能通过web查看
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                stopService(Intent(this, BylWebService::class.java))
//            }

            VpnServiceHelper.changeVpnRunningStatus(this, false)
        }
        else {
            val sp = getSharedPreferences(VPN_SP_NAME, Context.MODE_PRIVATE)
            val selectPackage = sp.getString(DEFAULT_PACKAGE_ID, null)
            val selectName = sp.getString(DEFAULT_PACAGE_NAME, null)
            if (selectPackage.isNullOrEmpty() && selectName.isNullOrEmpty()) {
                Toast.makeText(this, "请选择抓取应用", Toast.LENGTH_SHORT).show()
            }
            else {
                VpnServiceHelper.changeVpnRunningStatus(this, true)
                startService(Intent(this, BylWebService::class.java))
            }
        }
    }

    private fun selectApp() {
        val intent = Intent(this, PackageListActivity::class.java)
        startActivityForResult(intent, REQUEST_PACKAGE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == START_VPN_SERVICE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            VpnServiceHelper.startVpnService(applicationContext)
        } else if (requestCode == REQUEST_PACKAGE && resultCode == Activity.RESULT_OK) {
            val showInfo = data?.getParcelableExtra<ApkPackageInfo>(PackageListActivity.SELECT_PACKAGE)
            showInfo?.run {
                val sp = getSharedPreferences(VPN_SP_NAME, Context.MODE_PRIVATE)
                sp.edit().putString(DEFAULT_PACKAGE_ID, packageName)
                        .putString(DEFAULT_PACAGE_NAME, appName).apply()
            }
        }
    }

    private fun clearHistoryData() {
        ThreadProxy.getInstance().execute {
            val file = File(BASE_DIR)
            AppUtil.deleteFile(file, FileFilter { pathname ->
                return@FileFilter true
            })
        }
    }

}
