package com.ez.ertc

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.widget.RadioGroup
import android.widget.RadioGroup.OnCheckedChangeListener
import com.ez.baselib.utils.AppSpUtils
import com.ez.baselib.utils.LogUtil
import com.ez.basertc.RTCConstant.ErtcAudioCodeType
import com.ez.ertc.base.BaseActivity
import com.ez.ertc.meeting.ErtcEzmHelper
import com.ez.ertc.meeting.ui.JoinMeetingActivity
import com.ez.ertc.setting.HostSelectDialog
import com.ez.ertc.setting.SettingsActivity
import com.ez.ertcengine.ERTCEngine
import com.tencent.bugly.crashreport.CrashReport
import kotlinx.android.synthetic.main.activity_main.btn_enter
import kotlinx.android.synthetic.main.activity_main.btn_white_board
import kotlinx.android.synthetic.main.activity_main.edit_apiUrl
import kotlinx.android.synthetic.main.activity_main.edit_app_id
import kotlinx.android.synthetic.main.activity_main.edit_token
import kotlinx.android.synthetic.main.activity_main.imgSelectHost
import kotlinx.android.synthetic.main.activity_main.tv_version
import kotlinx.android.synthetic.main.activity_main.rg_audio_code_type

class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        edit_apiUrl.setText(AppSpUtils.getHost(this))
        edit_app_id.setText(AppSpUtils.getAppId(this))
        edit_token.setText(AppSpUtils.getToken(this))
        rg_audio_code_type.check(when(AppSpUtils.getAudioCodeType(this)) {
            0 -> R.id.rg_audio_code_type_aac
            1 -> R.id.rg_audio_code_type_opus
            else -> R.id.rg_audio_code_type_aac
        })
//        edit_secretkey.setText(ConstantApp.ertcSecretDebug)
//        edit_appkey.setText(ConstantApp.ertcAppKeyDebug)

        imgSelectHost.setOnClickListener {
            val hostSelectDialog = HostSelectDialog(this)
            hostSelectDialog.setSaveHostListener(object : HostSelectDialog.OnSaveHostListener {
                override fun onSaveHost(hostData: String) {
                    edit_apiUrl.setText(hostData)
                }
            })
            hostSelectDialog.show()
        }

        rg_audio_code_type.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.rg_audio_code_type_aac -> {
                    AppSpUtils.setAudioCodeType(this, ErtcAudioCodeType.AAC.value)
                }
                R.id.rg_audio_code_type_opus -> {
                    AppSpUtils.setAudioCodeType(this, ErtcAudioCodeType.OPUS.value)
                }
            }
        }

        btn_enter.setOnClickListener {
            val host: String = edit_apiUrl.text.toString().trim()
            val appId = edit_app_id.text.toString().trim()
            val token = edit_token.text.toString().trim()
            AppSpUtils.setAppId(applicationContext, appId)
            AppSpUtils.setToken(applicationContext, token)
//            val secretKey = edit_secretkey.text.toString().trim()
//            val appKey = edit_appkey.text.toString().trim()
            if (TextUtils.isEmpty(host) ||
                TextUtils.isEmpty(appId) ||
                TextUtils.isEmpty(token)
//                TextUtils.isEmpty(appKey)
            ) {
                toast("信息不能为空")
                return@setOnClickListener
            }
            AppSpUtils.saveHost(this, host)
            ErtcEzmHelper.getInstance().ertcTestAppIdDebug = appId
            ErtcEzmHelper.getInstance().ertcToken = token
            ErtcEzmHelper.getInstance().ertcAudioCodeType = when(AppSpUtils.getAudioCodeType(applicationContext)) {
                1 -> ErtcAudioCodeType.OPUS
                else -> ErtcAudioCodeType.AAC
            }

//            ErtcEzmHelper.getInstance().setErtcTestSecretDebug(secretKey)
//            ErtcEzmHelper.getInstance().setErtcTestAppKeyDebug(appKey)
            JoinMeetingActivity.start(this)
        }


        btn_white_board.setOnClickListener {
            startActivity(Intent(this, TestWhiteBoardActivity::class.java))
//            try {
//                val test = JniApi.jni.initSvgManager()
////                val test = ErtcBlackBoardNative().stringFromJNI()
//                Log.e("testest", test + "")
//                JniApi.jni.setLogPrintEnable(true)
//            } catch (e: Exception) {
//                e.printStackTrace()
//            }
        }
//        edit_room.setText("888888")
//        edit_userId.setText("6666")

        tv_version.text = ERTCEngine.getSDKVersion()

//        btn_speed_test.setOnClickListener{
//            val i = Intent(this, SpeedTestActivity::class.java)
//            startActivity(i)
//        }

//        btn_join.setOnClickListener {
//            checkPermission()
//        }

//        btn_init.setOnClickListener {
//            init()
//        }

//        btn_uninit.setOnClickListener {
//            ERTCEngine.destroyEngine();
//        }

//        btn_fetch_token.setOnClickListener {
//            if (MyApp.ertcEngine != null){
//                var userId = "0"
//                try {
//                    userId = edit_userId.text.toString()
//                }catch (e : Exception){
//                    toast("请输入合法的userId")
//                    return@setOnClickListener
//                }
//
//                val appId = edit_app_id.text.toString()
//                val secretKey = edit_secretkey.text.toString()
//                val roomId = edit_room.text.toString()
//                var rtctoken = ErtcGenerateTestUserSig.genTestUserSig(appId, secretKey, userId, roomId)
//                thread {
//                    tokenInfo = MyApp.ertcEngine!!.getToken(userId, roomId, rtctoken)
//                    runOnUiThread {
//                        toast("Fetch Token ${if(tokenInfo != null) "ok" else "error"}")
//                    }
//                }
//            }else{
//                toast("请先初始化")
//            }
//        }


        //bugly
        CrashReport.initCrashReport(applicationContext, "7de837608b", true)
        LogUtil.d("test", "test")
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        val inflater = menuInflater
        inflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle presses on the action bar items
        return when (item.itemId) {
            R.id.action_settings -> {
                startActivity(Intent(this, SettingsActivity::class.java))
                true
            }

            else -> super.onOptionsItemSelected(item)
        }
    }

//    override fun onRequestPermissionsResult(
//        requestCode: Int,
//        permissions: Array<out String>,
//        grantResults: IntArray
//    ) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//        if (1012 == requestCode && grantResults.isNotEmpty()) {
//            var isGranted = true
//            for (grantResult in grantResults) {
//                if (grantResult != PackageManager.PERMISSION_GRANTED) {
//                    isGranted = false
//                    break
//                }
//            }
//            if (isGranted) {
//                onPermissionsGranted()
//            } else {
//                toast("您拒绝授予视频会议功能所需的权限，该功能无法使用")
//            }
//        }
//    }

//    private fun init(){
//        var host: String = edit_apiUrl.text.toString()
//        Config.saveHost(this, host)
//
//        val config = RTCConstant.RTCEngineConfig()
//        if (TextUtils.isEmpty(edit_app_id.text.toString()) || TextUtils.isEmpty(edit_access_token.text.toString())){
//            toast("appId及accessToken不能为空")
//            return
//        }
//        config.appId = edit_app_id.text.toString()
//        config.accessToken = edit_access_token.text.toString()
//        config.context = applicationContext
//        config.logPath = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)?.path
//        GlobalScope.launch {
//            ERTCEngine.init(config, object : ERTCEngine.OnInitListener {
//                override fun onInitialization(engine: ERTCEngine?) {
//                    MyApp.ertcEngine = engine
//                    engine?.setRTCListener(MyApp.listener)
//                    runOnUiThread {
//                        toast("Init OK")
//                    }
//                }
//
//                override fun onError(code: Int) {
//                    runOnUiThread {
//                        toast("Init failed error[$code]")
//                    }
//                }
//
//            })
//        }
//
//    }

//    private fun checkPermission(){
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            val canAccessCamera: Boolean = checkThisPermission(Manifest.permission.CAMERA)
//            val canAccessRecord: Boolean = checkThisPermission(Manifest.permission.RECORD_AUDIO)
//            if (canAccessCamera && canAccessRecord) {
//                onPermissionsGranted()
//            } else {
//                val permissionsList = ArrayList<String>()
//                if (!canAccessCamera) {
//                    permissionsList.add(Manifest.permission.CAMERA)
//                }
//                if (!canAccessRecord) {
//                    permissionsList.add(Manifest.permission.RECORD_AUDIO)
//                }
//                val permissions = arrayOfNulls<String>(permissionsList.size)
//                for (i in permissionsList.indices) {
//                    permissions[i] = permissionsList[i]
//                }
//                requestPermissions(permissions, 1012)
//            }
//        } else {
//            onPermissionsGranted()
//        }
//    }
//
//    private fun onPermissionsGranted() {
//
//        if (tokenInfo == null || TextUtils.isEmpty(tokenInfo!!.token)){
//            toast("请先获取token")
//            return
//        }
//        val info = RTCConstant.EnterParam()
//        try {
//            info.userId = edit_userId.text.toString()
//        }catch (e : Exception){
//            toast("请输入合法的userId")
//            return
//        }
//        info.roomId = edit_room.text.toString()
//        info.token = tokenInfo!!.token
//
//        val i = Intent(this, CallActivity::class.java)
//        i.putExtra(ConstantApp.ACTION_KEY_ENTER_INFO, info)
//        startActivity(i)
//
//    }
//
//    private fun checkThisPermission(permissionName: String): Boolean {
//        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            checkSelfPermission(permissionName) == PackageManager.PERMISSION_GRANTED
//        } else {
//            true
//        }
//    }

}