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.secspace.lib.common.dialog.LoadingDialog
import com.secspace.lib.common.function.SwitchInMdm
import com.secspace.lib.common.utils.IntentUtil
import kotlinx.android.synthetic.main.activity_app_manager.*
import kotlinx.coroutines.*

class AppChooseActivity : BaseActivity() {
    var mAppInfoAdapterSystemApp: AppChooseListAdapter? = null
    var mAppInfoAdapterUserApp: AppChooseListAdapter? = null
    var job: Job? = 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)
        LoadingDialog.getInstance(this).show("加载中")
        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() {
        job = 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) {
            LoadingDialog.getInstance(mContext).dismiss()
            mAppInfoAdapterUserApp?.readResult(mAppContext)
            mAppInfoAdapterSystemApp?.readResult(mAppContext)
            mAppInfoAdapterSystemApp?.notifyDataSetChanged()
            mAppInfoAdapterUserApp?.notifyDataSetChanged()
        }
    }

    fun close(view: View?) {
        job?.cancel()
        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 -> {
                job?.cancel()
                finish()
            }
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        job?.cancel()
        finish()
    }
}