/*
 * 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.todos

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.ContactsContract
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import rasel.lunar.launcher.LauncherActivity.Companion.lActivity
import rasel.lunar.launcher.R
import rasel.lunar.launcher.databinding.ListItemBinding
import rasel.lunar.launcher.databinding.TodoDialogBinding
import rasel.lunar.launcher.helpers.UniUtils.Companion.copyToClipboard
import rasel.lunar.launcher.utils.BLog
import rasel.lunar.launcher.utils.getContactId
import rasel.lunar.launcher.workers.RecentCall
import java.util.*
import kotlin.collections.ArrayList


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

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

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

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

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: MissedCallsHolder, position: Int) {
        val todo = callList[position]
        holder.view.itemText.text = "\u25CF  ${if(todo.name.equals("unknown")) todo.number else { todo.name}} , ${todo.typeString} : ${todo.count} : ${todo.date}"

        /* multiline texts are enabled for TodoManager */
        holder.view.itemText.isSingleLine = false
        /* launch edit or update dialog on item click */
        holder.view.itemText.setOnClickListener { updateDialog(position) }
        /* copy texts on long click */
        holder.view.itemText.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 MissedCallsHolder(var view: ListItemBinding) : 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)
//            }
//        }
    }

    fun updateData(newList: ArrayList<RecentCall>) {
        val diffUtilResult = DiffUtil.calculateDiff(MissedCallDiffUtil(callList, newList))
        diffUtilResult.dispatchUpdatesTo(this)
//        callList.clear()
//        callList.addAll(newList)
    }

}

internal class MissedCallDiffUtil(
    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]
}

