/*
 * 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.net.Uri
import android.provider.CallLog
import android.provider.ContactsContract
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import rasel.lunar.launcher.LauncherActivity.Companion.lActivity
import rasel.lunar.launcher.R
import rasel.lunar.launcher.databinding.CalllogItemBinding
import rasel.lunar.launcher.utils.getContactId
import rasel.lunar.launcher.workers.RecentCall


internal class RecentCallsAdapter(
    private val callList: ArrayList<RecentCall>,
    private val context: Context) : RecyclerView.Adapter<RecentCallsAdapter.RecentCallsHolder>() {

    private val currentFragment = lActivity!!.supportFragmentManager.findFragmentById(R.id.mainFragmentsContainer)

    override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): RecentCallsHolder {
        val binding = CalllogItemBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false)
        return RecentCallsHolder(binding)
    }

    override fun getItemCount(): Int {
//        BLog.LOGE("callList.size >>> ${callList.size}")
        return callList.size
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: RecentCallsHolder, position: Int) {
        val todo = callList[position]
        holder.view.name.text = if(todo.name.equals("unknown")) todo.number else { todo.name}

        when (todo.type) {
//            CallLog.Calls.INCOMING_TYPE -> { dir = "INCOMING_TYPE" }
//            CallLog.Calls.OUTGOING_TYPE -> { dir = "OUTGOING_TYPE" }
            CallLog.Calls.MISSED_TYPE -> { holder.view.root.isSelected = true }
//            CallLog.Calls.VOICEMAIL_TYPE -> { dir = "VOICEMAIL_TYPE" }
//            CallLog.Calls.REJECTED_TYPE -> { dir = "REJECTED_TYPE" }
//            CallLog.Calls.BLOCKED_TYPE -> { dir = "BLOCKED_TYPE" }
//            CallLog.Calls.ANSWERED_EXTERNALLY_TYPE -> { dir = "ANSWERED_EXTERNALLY_TYPE" }
            else -> { holder.view.root.isSelected = false }
        }
//        "\u25CF  ${} , ${todo.typeString} : ${todo.count} : ${todo.date}"
        holder.view.type.text = todo.typeString
        /* multiline texts are enabled for TodoManager */
        holder.view.date.text = todo.date
        /* launch edit or update dialog on item click */
        holder.view.root.setOnClickListener { updateDialog(position) }
        /* copy texts on long click */
        holder.view.root.setOnLongClickListener {

//            copyToClipboard(context, todo.name)
            var cId = getContactId(lActivity!!.contentResolver, todo.number)
            if (cId != null && cId.length > 0) {
                var intent = Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(ContactsContract.Contacts.CONTENT_URI.toString() + "/" + cId));
                lActivity?.startActivity(intent);
            } else {
                lActivity?.startActivity(Intent(Intent.ACTION_DIAL, Uri.parse("tel:${todo.number}")))
            }

            true
        }

    }

    inner class RecentCallsHolder(var view: CalllogItemBinding) : RecyclerView.ViewHolder(view.root)

    /* update dialog */
    private fun updateDialog(position: Int) {
//        val bottomSheetDialog = BottomSheetDialog(lActivity!!, R.style.BottomSheetDialog)
//        val dialogBinding = TodoDialogBinding.inflate(LayoutInflater.from(context))
//        bottomSheetDialog.setContentView(dialogBinding.root)
//        bottomSheetDialog.show()
//        bottomSheetDialog.dismissWithAnimation = true
//
//        val databaseHandler = DatabaseHandler(context)
//        val todo = databaseHandler.todos[position]
//
//        dialogBinding.apply {
//            deleteAllConfirmation.visibility = View.GONE
//            todoInput.setText(todo.name)
//            todoCancel.text = context.getString(R.string.delete)
//            todoCancel.setTextColor(ContextCompat.getColor(context, android.R.color.holo_red_light))
//            todoOk.text = context.getString(R.string.update)
//        }
//
//        /* delete the item */
//        dialogBinding.todoCancel.setOnClickListener {
//
//        }
//
//        /* update the item */
//        dialogBinding.todoOk.setOnClickListener {
//            val updatedTodoString = Objects.requireNonNull(dialogBinding.todoInput.text).toString().trim { it <= ' ' }
//            if (updatedTodoString.isNotEmpty()) {
//                todo.name = updatedTodoString
//                databaseHandler.updateTodo(todo)
//                bottomSheetDialog.dismiss()
//            } else {
//                dialogBinding.todoInput.error = context.getString(R.string.empty_text_field)
//            }
//        }
    }
    var layoutManager : GridLayoutManager? = null
    var recyclerView: RecyclerView? = null
    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        layoutManager = recyclerView.layoutManager as? GridLayoutManager
        this.recyclerView = recyclerView
    }

    fun updateData(newList: Collection<RecentCall>) {
        val diffUtilResult = DiffUtil.calculateDiff(RecentCallDiffUtil(callList, newList.toList()))
        diffUtilResult.dispatchUpdatesTo(this).apply {
            val visibleItemCount = (layoutManager?.findLastVisibleItemPosition() ?: 0) - (layoutManager?.findFirstVisibleItemPosition() ?: 0)
            if (visibleItemCount > 0) {
                this@RecentCallsAdapter.notifyItemRangeChanged(0, visibleItemCount)
                recyclerView?.scrollToPosition(0)
            }
        }
        callList.clear()
        callList.addAll(newList)
    }

}

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

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

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

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

