package com.feasycom.feasywifi.ui

import android.content.ClipData
import android.content.ClipboardManager
import android.os.Bundle
import android.util.TypedValue
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import cat.ereza.customactivityoncrash.CustomActivityOnCrash
import cat.ereza.customactivityoncrash.config.CaocConfig
import com.feasycom.feasywifi.R
import com.feasycom.feasywifi.databinding.ActivityCrashBinding
import com.feasycom.feasywifi.databinding.ActivityMainBinding

/**
 * author : Android 轮子哥
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2019/06/27
 * desc   : 崩溃捕捉界面
 */
class CrashActivity : BaseActivity<ActivityCrashBinding>(){

    private var mConfig: CaocConfig? = null

    private var mDialog: AlertDialog? = null

    override fun getViewBinding() = ActivityCrashBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mConfig = CustomActivityOnCrash.getConfigFromIntent(intent)

        mBinding.btnCrashLog.setOnClickListener {
            if (mDialog == null) {
                mDialog = AlertDialog.Builder(this)
                    .setTitle("错误信息")
                    .setMessage(
                        CustomActivityOnCrash.getAllErrorDetailsFromIntent(
                            this,
                            intent
                        )
                    )
                    .setPositiveButton("关闭", null)
                    .setNeutralButton("复制错误信息") { dialog, which -> copyErrorToClipboard() }
                    .create()
            }
            mDialog?.show()
            val textView: TextView? = mDialog?.findViewById<TextView>(R.id.message)

            textView?.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)
        }

        mBinding.btnCrashRestart.setOnClickListener {
            mConfig?.let {
                CustomActivityOnCrash.restartApplication(this, it)
            }
        }




    }

    /**
     * 复制报错信息到剪贴板
     */
    private fun copyErrorToClipboard() {
        val errorInformation = CustomActivityOnCrash.getAllErrorDetailsFromIntent(
            this,
            intent
        )
        (getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
            ClipData.newPlainText(
                "错误信息",
                errorInformation
            )
        )
    }

}