/*
 * 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.annotation.SuppressLint
import android.content.pm.PackageManager
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import io.realm.kotlin.types.RealmObject
import io.realm.kotlin.types.annotations.PrimaryKey
import rasel.lunar.launcher.databinding.ContactItemBinding
import rasel.lunar.launcher.utils.BLog
import rasel.lunar.launcher.utils.JamoUtils
import rasel.lunar.launcher.workers.RecentCallGetter
import java.util.Date


internal class ContactAdapter (
    private val packageManager: PackageManager,
    private val fragmentManager: FragmentManager) : RecyclerView.Adapter<ContactAdapter.ContactViewHolder>() {

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

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

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

    override fun onBindViewHolder(holder: ContactViewHolder, i: Int) {
        val item = oldList[i]
//        BLog.LOGE("name >>> ${item.name} :: ${item.touchCount} :: ${RecentCallGetter.dateFormat.format(
//            Date(item.lastedTouchDateTime)
//        )}")

        holder.view.apply {
            name.text = item.name
            number.text= item.phoneNumber
        }
        holder.view.root.apply {
            /* on click - open app */
            setOnClickListener {
                ContactMenu().show(fragmentManager, item.id.toString())
            }

            /* on long click - open app menu */
            setOnLongClickListener {
//                BLog.LOGE("item.id.toString() >> ${item.id.toString()}")
                ContactMenu().show(fragmentManager, item.id.toString())
                true
            }
        }
    }

    override fun getItemCount(): Int = oldList.size

    inner class ContactViewHolder(var view: ContactItemBinding) : RecyclerView.ViewHolder(view.root)

    /* update app list */
    fun updateData(newList: List<SimpleContact>) {
        synchronized(oldList) {
            try {
                val diffUtilResult = DiffUtil.calculateDiff(ContactDiffUtil(oldList, newList))
                diffUtilResult.dispatchUpdatesTo(this)
                oldList.clear()
                oldList.addAll(newList)
                newList.size.let {
                    appsSize = it
                }
            }catch (e : IndexOutOfBoundsException) {

            }
        }
    }

    /* update text gravity (alignment) */
    @SuppressLint("RtlHardcoded", "NotifyDataSetChanged")
    fun updateGravity(gravity: Int){
        /* the first check is to avoid calling notifyDataSetChanged() everytime */
        if (gravity != appGravity &&
            (gravity == Gravity.LEFT || gravity == Gravity.CENTER || gravity == Gravity.RIGHT)) {
            appGravity = gravity
            notifyDataSetChanged()
        }
    }

    fun hideItem(idx: Int) {

    }
}
class SimpleContact : RealmObject {
    @PrimaryKey
    var id : String? = ""
    var name : String? = ""
    var chosung : String? = ""
    var phoneNumber : String? = ""
    var touchCount = 0
    var lastedTouchDateTime = 0L

    constructor(id: String, name: String, phoneNumber: String) {
        this.id = id
        this.name = name
        this.phoneNumber = phoneNumber
        chosung = JamoUtils.split(name).joinToString("")
    }

    constructor()

}

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

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

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

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