/*
 * Lunar Launcher
 * Copyright (C) 2022 Md Rasel Hossain
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package rasel.lunar.launcher.apps

import android.content.pm.PackageManager
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import io.realm.kotlin.ext.query
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import rasel.lunar.launcher.LauncherActivity.Companion.lActivity
import rasel.lunar.launcher.R
import rasel.lunar.launcher.apps.IconPackManager.Companion.getDrawableIconForPackage
import rasel.lunar.launcher.databinding.AppsChildBinding
import rasel.lunar.launcher.model.AppInfo
import rasel.lunar.launcher.workers.WorkersDb


internal class AppsAdapter(
    private val layoutType: Int,
    private val packageManager: PackageManager,
    private val fragmentManager: FragmentManager,
    private val appsCount: TextView) : RecyclerView.Adapter<AppsAdapter.AppsViewHolder>() {

    private var oldList = mutableListOf<AppInfo>()
//    private var appGravity: Int = Gravity.CENTER

    companion object {
        @JvmStatic var appsSize: Int? = null
    }

    override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): AppsViewHolder =
        AppsViewHolder(AppsChildBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false))

    override fun onBindViewHolder(holder: AppsViewHolder, i: Int) {
        val item = oldList[i]




        holder.view.apply {
            childTextview.text = item.appName
            appIconTwo.visibility = View.VISIBLE

            MainScope().async {
                getDrawableIconForPackage(item.pkgName, packageManager.getApplicationIcon(item.pkgName!!)) {
                    appIconTwo.post { appIconTwo.setImageDrawable(it) }
                } }
            childTextview.apply {
                gravity = Gravity.CENTER
                setTextSize(TypedValue.COMPLEX_UNIT_PX, lActivity!!.resources.getDimension(R.dimen.twelve))
            }
        }

        holder.view.root.apply {
            /* on click - open app */
            setOnClickListener {
                WorkersDb.getRealm().apply {
                    writeBlocking {
                        var result = query<AppInfo>("pkgName == $0",item.pkgName).find()
                        if(result.size > 0) {
                            val app = result.first()
                            app.clickCount = app.clickCount + 1
                            app.lastUseDate = Math.max(app.lastUseDate, System.currentTimeMillis())
                        }
                    }
                }
                context.startActivity(packageManager.getLaunchIntentForPackage(item.pkgName!!))
            }

            /* on long click - open app menu */
            setOnLongClickListener {
                AppMenu().apply {
                }.show(fragmentManager, item.pkgName)
                true
            }
        }
    }

    override fun getItemCount(): Int = oldList.size

    inner class AppsViewHolder(var view: AppsChildBinding) : RecyclerView.ViewHolder(view.root)

    /* update app list */
    fun updateData(newList: List<AppInfo>) {
        val diffUtilResult = DiffUtil.calculateDiff(AppsDiffUtil(oldList, newList))
//
        diffUtilResult.dispatchUpdatesTo(this)
        oldList.clear()
        oldList.addAll(newList)
        newList.size.let {
            appsCount.text = it.toString()
            appsSize = it
        }
    }
}


internal class AppsDiffUtil(
    private val oldList: List<AppInfo>, private val newList: List<AppInfo>
) : DiffUtil.Callback() {

    override fun getOldListSize(): Int = oldList.size
    override fun getNewListSize(): Int = newList.size

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
        oldList[oldItemPosition].pkgName == newList[newItemPosition].pkgName

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
        oldList[oldItemPosition] == newList[newItemPosition]
}
