package com.android.launcher3.function.setting

import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.ResolveInfo
import android.os.Bundle
import android.os.Handler
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.LinearLayoutManager.HORIZONTAL
import android.support.v7.widget.LinearLayoutManager.VERTICAL
import android.util.Log
import android.view.View
import com.android.launcher3.BaseActivity
import com.android.launcher3.R
import com.android.launcher3.settings.AppChooseListAdapter
import com.android.launcher3.settings.AppChooseListAdapter.SYSTEM_APP_FLAG
import com.android.launcher3.settings.AppChooseListAdapter.USER_APP_FLAG
import com.android.launcher3.settings.AppModel
import com.android.launcher3.settings.BaseRecyclerViewAdapter
import com.secspace.lib.common.dialog.SwitcherDialog
import com.secspace.lib.common.function.SwitchInMdm
import com.secspace.lib.common.utils.IntentUtil
import com.secspace.lib.common.utils.Prefs
import kotlinx.android.synthetic.main.activity_app_manager.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class AppChooseActivity : BaseActivity() {
    var mAppInfoAdapterSystemApp: AppChooseListAdapter? = null
    var mAppInfoAdapterUserApp: AppChooseListAdapter? = null

    private val mSystemApps: MutableList<AppModel> = ArrayList()
    private val mUserApps: MutableList<AppModel> = ArrayList()
    private lateinit var mContext: Context

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

    fun initView() {
        tv_setting_title.setText(R.string.edu_item_icon)
        SwitcherDialog.getInstance(this).show("加载应用中", "Loading")
        mAppInfoAdapterSystemApp = AppChooseListAdapter(SYSTEM_APP_FLAG)
        mAppInfoAdapterSystemApp?.setItemViewId(R.layout.item_app_choose_list)
        val linearLayoutManager = LinearLayoutManager(this, VERTICAL, false)
        recyclerview_system.layoutManager = linearLayoutManager
        recyclerview_system.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
        recyclerview_system.adapter = mAppInfoAdapterSystemApp
        mAppInfoAdapterUserApp = AppChooseListAdapter(USER_APP_FLAG)
        mAppInfoAdapterUserApp?.setItemViewId(R.layout.item_app_choose_list)
        val linearLayoutManagerUser = LinearLayoutManager(this, VERTICAL, false)
        recyclerview_user.layoutManager = linearLayoutManagerUser
        recyclerview_user.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
        recyclerview_user.adapter = mAppInfoAdapterUserApp
        mAppInfoAdapterSystemApp?.list = mSystemApps
        mAppInfoAdapterUserApp?.list = mUserApps
    }

    private fun loadData() {
        GlobalScope.launch(Dispatchers.IO) {
            val resolveInfos: List<ResolveInfo> = packageManager.queryIntentActivities(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER), 0)
            val apps: MutableList<ApplicationInfo> = ArrayList()
            resolveInfos.forEach {
                apps.add(packageManager.getApplicationInfo(it.activityInfo.packageName, 0))
            }
            val items = ArrayList<AppModel>(apps.size)
            apps.forEach {
                val app = AppModel(mAppContext, it)
                items.add(app)
            }
            loadFinished(items)
        }
    }

    private suspend fun loadFinished(appModels: List<AppModel>) {
        mSystemApps.clear()
        mUserApps.clear()
        appModels.forEach {
            if (it.appInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0) {
                mSystemApps.add(it)
            } else {
                if (it.applicationPackageName != this.packageName) {
                    mUserApps.add(it)
                }
            }
        }
        withContext(Dispatchers.Main) {
            SwitcherDialog.getInstance(mContext).dismiss("Loading")
            mAppInfoAdapterUserApp?.readResult(mAppContext)
            mAppInfoAdapterSystemApp?.readResult(mAppContext)
            mAppInfoAdapterSystemApp?.notifyDataSetChanged()
            mAppInfoAdapterUserApp?.notifyDataSetChanged()

        }
    }

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

    fun btnClick(view: View?) {
        when (view?.id) {
            R.id.btn_sure -> {
                mAppInfoAdapterSystemApp?.saveResult(mAppContext)
                mAppInfoAdapterUserApp?.saveResult(mAppContext)
                SwitchInMdm.addDisallowedRunningApp(this)
                IntentUtil.startEduLauncher(this)
                finish()
            }
            R.id.btn_cancel -> {
                finish()
            }
        }
    }
}