/*
 * 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.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import rasel.lunar.launcher.LauncherActivity.Companion.lActivity
import rasel.lunar.launcher.R
import rasel.lunar.launcher.databinding.SmsItemBinding
import rasel.lunar.launcher.utils.getContactName
import rasel.lunar.launcher.workers.RecentSms
import java.text.SimpleDateFormat
import java.util.Date


internal class SmsLogsAdapter(
    private val smsList: ArrayList<RecentSms>,
    private val context: Context) : RecyclerView.Adapter<SmsLogHolder>() {

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

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

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

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: SmsLogHolder, position: Int) {
        val todo = smsList[position]
        var name = getContactName(lActivity!!.contentResolver,todo.person)
        if (name == null) {
            getContactName(lActivity!!.contentResolver,todo.addr)
        }
        if(todo.isMms) {
            var body = todo.texts?.joinToString("\n")?.replace("\n"," ")
            body =  if (body?.length ?: 0 > 60) body?.substring(0,60).plus("...") else body
            holder.view.itemText.text = "\u25CF  ${if(name != null && name.length > 0) name else if(todo.person != null && todo.person.length > 0){todo.person} else todo.addr}  : ${
                SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(
                    Date(
                        Math.max(
                            todo.pstDate.toLong(),
                            todo.rcvDate.toLong()
                        )
                    )
                )
            } : ${todo.type}"
            holder.view.contents.text = "${body}"
        } else {
            holder.view.itemText.text = "\u25CF  ${if(name != null && name.length > 0) name else if(todo.person != null && todo.person.length > 0){todo.person} else todo.addr}  : ${
                SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(
                    Date(
                        Math.max(
                            todo.pstDate.toLong(),
                            todo.rcvDate.toLong()
                        )
                    )
                )
            } : ${todo.type}"




            holder.view.contents.text = "${todo.body}"
        }



        /* 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 {
            var intent =  Intent(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse("smsto:" + Uri.encode(todo.addr)));
            lActivity?.startActivity(intent);
            true
        }

        holder.view.root.isActivated = if(holder.view.itemText.text.contains("#CMAS#")) true else false
    }



    fun updateData(newList: List<RecentSms>) {
        val diffUtilResult = DiffUtil.calculateDiff(SmsDiffUtil(smsList, newList))
        diffUtilResult.dispatchUpdatesTo(this)
        smsList.clear()
        smsList.addAll(newList)
    }

    /* 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)
//            }
//        }
    }

}
class SmsLogHolder(var view: SmsItemBinding) : RecyclerView.ViewHolder(view.root)
internal class SmsDiffUtil(
    private val oldList: List<RecentSms>, private val newList: List<RecentSms>
) : DiffUtil.Callback() {

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

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

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