package com.android.launcher3.function.setting

import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.GridLayout
import android.widget.LinearLayout
import android.widget.TextView
import com.android.launcher3.BaseActivity
import com.android.launcher3.R
import com.android.launcher3.mdm.DisableCompat
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView
import com.secspace.lib.common.dialog.SwitcherDialog
import com.secspace.lib.common.event.ChangeWallPaperEvent
import com.secspace.lib.common.utils.PkgManager
import com.secspace.lib.common.utils.Prefs
import com.secspace.lib.common.utils.ToastUtil
import com.secspace.lib.common.utils.UninstallUtil.removeForbidden
import com.secspace.lib.common.utils.UninstallUtil.uninstallService
import com.secspace.lib.common.utils.dp2px
import kotlinx.android.synthetic.main.activity_setting.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

class AdminSettingActivity : BaseActivity() {
    private var mContext: Context? = null
    private var icon: QMUICommonListItemView? = null
    private var reinforce: QMUICommonListItemView? = null
    private var pwdManager: QMUICommonListItemView? = null
    private var allowApp: QMUICommonListItemView? = null
    private var uninstall: QMUICommonListItemView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setAndroidNativeLightStatusBar(true)
        setContentView(R.layout.activity_setting)
        mContext = this
        initView()
    }

    private fun initView() {
        tv_setting_title.setText(R.string.edu_title_setting)
        icon = grouplistview.createItemView(null,
                getString(R.string.edu_item_icon),
                null,
                GridLayout.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON,
                dp2px(48f))
        reinforce = grouplistview.createItemView(null,
                getString(R.string.edu_item_reinforce),
                null,
                GridLayout.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE,
                dp2px(48f))
        pwdManager = grouplistview.createItemView(null,
                getString(R.string.edu_item_pwd_manager),
                null,
                GridLayout.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON,
                dp2px(48f))
        allowApp = grouplistview.createItemView(null,
                getString(R.string.edu_item_allow_app),
                null,
                GridLayout.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_SWITCH,
                dp2px(48f))
        uninstall = grouplistview.createItemView(null,
                getString(R.string.edu_item_uninstall),
                null,
                GridLayout.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON,
                dp2px(48f))
//        reinforce?.switch?.setOnCheckedChangeListener { _, isChecked ->
//            Prefs.setReinforce(mContext, isChecked)
//            if (isChecked) showTipDialog({ reinforce() }, { reinforce?.switch?.isChecked = false }, getString(R.string.edu_reinforce))
//        }
        allowApp?.switch?.setOnCheckedChangeListener { _, isChecked ->
            Prefs.setAllowNewApp(mContext, isChecked)
            if (isChecked) showTipDialog({ }, { allowApp?.switch?.isChecked = false }, getString(R.string.open_new_app_tip))
        }
        QMUIGroupListView.newSection(this)
                .addItemView(icon) {startActivity(Intent(mContext, AppChooseActivity::class.java))}
                .addItemView(reinforce) {ToastUtil.showShort(mContext, R.string.edu_toast_wait)}
                .addItemView(allowApp) {}
                .addItemView(pwdManager) { startActivity(Intent(mContext, SettingPwdActivity::class.java)) }
                .addItemView(uninstall) { showTipDialog({ uninstall() }, { }, getString(R.string.edu_uninstall_tip)) }
                .addTo(grouplistview)
    }

    fun close(view: View?) {
        finish()
    }

    private fun reinforce() {
        val packages: MutableList<String> = PkgManager.getInstance(mContext).queryLauncherPackages()
        packages.remove(mContext?.packageName)
        if (packages.isNotEmpty()) {
            Prefs.setHideLauncherPackages(mContext, packages)
        }
        for (packageName in packages) {
            DisableCompat.disableApplication(mContext, packageName)
        }
    }

    private fun uninstall() {
        GlobalScope.launch(Dispatchers.Main) {
            SwitcherDialog.getInstance(mContext).show(getString(R.string.edu_uninstall), "unInstall")
            removeForbidden(mContext)
            delay(1000)
            uninstallService(mContext)
            delay(800)
            SwitcherDialog.getInstance(mContext).dismiss("unInstall")
        }
    }

    override fun onActivityResult(
            requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == REQUEST_PICK_WALLPAPER) {
            if (resultCode == Activity.RESULT_OK) {
                val selectedImage = data!!.data
                EventBus.getDefault().postSticky(ChangeWallPaperEvent(selectedImage))
                ToastUtil.showShort(this, "壁纸修改成功")
            }
        }
    }

    private inline fun showTipDialog(crossinline sure: () -> Unit, crossinline cancel: () -> Unit, text: String) {
        val alertDialog: AlertDialog
        val textView = TextView(this)
        val view = LayoutInflater.from(this).inflate(R.layout.item_ll, null)
        textView.text = text
        val ll = view.findViewById<LinearLayout>(R.id.item_ll)
        ll.addView(textView)
        alertDialog = AlertDialog.Builder(this)
                .setTitle(getString(R.string.tip))
                .setCancelable(false)
                .setView(view)
                .setNegativeButton(R.string.work_cancel) { dialog, _ ->
                    dialog.dismiss()
                    cancel()
                }
                .setPositiveButton(R.string.work_sure) { dialog, _ ->
                    run {
                        dialog.dismiss()
                        sure()
                    }
                }
                .create()
        if (!alertDialog.isShowing) {
            alertDialog.show()
        }
    }

    companion object {
        private const val REQUEST_PICK_WALLPAPER = 10
    }
}