/*
 * 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.home.adapters

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import rasel.lunar.launcher.LauncherActivity.Companion.lActivity
import rasel.lunar.launcher.databinding.ListItemWithBinding
import rasel.lunar.launcher.model.NotificationItem
import rasel.lunar.launcher.utils.BLog
import rasel.lunar.launcher.workers.WorkersDb
import java.text.SimpleDateFormat
import java.util.Date


internal class NotificationItemAdapter (
    private val context: Context) : RecyclerView.Adapter<NotiHolder>() {
    private var notiItems: ArrayList<NotificationItem> = arrayListOf()
    override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): NotiHolder {
        val binding = ListItemWithBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false)
        return NotiHolder(binding)
    }

    override fun getItemCount(): Int {
        return notiItems.size
    }

    val dateFormat = SimpleDateFormat("hh:mm / yy - MM - dd")

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: NotiHolder, position: Int) {
        val appInfo = notiItems[position]
        try {
            holder.view.circlePreview.visibility = View.VISIBLE
            var param = holder.view.circlePreview.layoutParams
            holder.view.circlePreview.layoutParams = ConstraintLayout.LayoutParams(120,param.height)
            val d: Drawable = context.packageManager.getApplicationIcon(appInfo.pkgName!!)
            holder.view.circlePreview.setImageDrawable(d)
            holder.view.title.text = appInfo.tikerMsg ?: "${appInfo.selfDisplayName} ${appInfo.subtext}"
            holder.view.desc.text = "${appInfo.pkgName} ${appInfo.title}"
            holder.view.date.text = dateFormat.format(Date(appInfo.postTime))
            holder.view.circlePreview.setOnLongClickListener {
                WorkersDb.getRealm().writeBlocking {
                    delete(query<NotificationItem>(NotificationItem::class).query("pkgName == $0",appInfo.pkgName).find())
                }
                lActivity?.packageManager?.apply {
                    context.startActivity(getLaunchIntentForPackage(appInfo.pkgName!!))
                }
                true
            }


        } catch (e: PackageManager.NameNotFoundException) {
            return
        }

    }

    fun updateData(newList: List<NotificationItem>) {
        try {
            DiffUtil.calculateDiff(NotiItemDiffUtil(notiItems, newList)).apply {

            }.dispatchUpdatesTo(this).apply {
//                notifyItemRangeChanged(0,10)
            }
            notiItems.clear()
            notiItems.addAll(newList)
        }catch ( e : Exception) {
            e.printStackTrace()
        }
    }


}

internal class NotiHolder(var view: ListItemWithBinding) : RecyclerView.ViewHolder(view.root)
internal class NotiItemDiffUtil(
    var oldList: List<NotificationItem>, var newList: List<NotificationItem>
) : DiffUtil.Callback() {

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

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean  =
        oldList[oldItemPosition].uniq_id == if (newList.size > newItemPosition) newList[newItemPosition].uniq_id else ""

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
        oldList[oldItemPosition].uniq_id == if (newList.size > newItemPosition) newList[newItemPosition].uniq_id else ""
}
