/*
 * 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.feeds.rss

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
import rasel.lunar.launcher.LauncherActivity.Companion.lActivity
import rasel.lunar.launcher.databinding.ListItemWithBinding
import rasel.lunar.launcher.model.RssDataInterface
import rasel.lunar.launcher.model.RssDataType
import rasel.lunar.launcher.model.JGuru
import rasel.lunar.launcher.home.adapters.RssItemDiffUtil
import java.net.URLEncoder
import java.nio.charset.Charset
import java.text.SimpleDateFormat
import java.util.Date


internal class RssAdapter<T : RssDataInterface>(private val context: Context) :
    RecyclerView.Adapter<RssViewHolder>() {
    var items: ArrayList<RssDataInterface> = arrayListOf<RssDataInterface>()
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RssViewHolder {
        val binding = ListItemWithBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return RssViewHolder(binding)
    }

    override fun getItemCount(): Int = items.size
    val dateFormat = SimpleDateFormat("hh:mm / yy - MM - dd")
    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: RssViewHolder, position: Int) {
        val item = items[position]
        holder.view.circlePreview.visibility = View.GONE
        if (item.category() == RssDataType.TAGS) {
            var txts = item.title().split("(")
            holder.view.title.text = "\n".plus(txts[0])
            holder.view.title.gravity = Gravity.CENTER
            if (txts.size > 1) {
                holder.view.desc.text = "(".plus(txts[1])
                holder.view.desc.gravity = Gravity.RIGHT
                holder.view.desc.visibility = View.VISIBLE

            } else {
                holder.view.desc.text = ""
            }
            holder.view.date.visibility = View.GONE
            holder.view.date.text = ""
        } else {
            holder.view.title.gravity = Gravity.CENTER_VERTICAL.plus(Gravity.RIGHT)
            holder.view.desc.gravity = Gravity.CENTER_VERTICAL.plus(Gravity.RIGHT)
            holder.view.date.gravity = Gravity.CENTER_VERTICAL.plus(Gravity.RIGHT)
            holder.view.title.text = item.title()
            if (item.pubDate() > 1000L) {
                holder.view.date.text = dateFormat.format(Date(item.pubDate()))
            }
            holder.view.desc.text = item.description()
            holder.view.desc.visibility = View.VISIBLE
            holder.view.date.visibility = View.VISIBLE
        }


        if (item.thumbnailUrl().length ?: 0 > 6) {
            Picasso.get().load(item.thumbnailUrl()).into(holder.view.circlePreview)
        }

        holder.view.root.setOnClickListener {
            holder.view.circlePreview.visibility = View.VISIBLE
            holder.view.circlePreview.postDelayed({
                holder.view.circlePreview.visibility = View.GONE
            },500L)
        }

        holder.view.root.setOnLongClickListener {
            if(item is JGuru) {
                openOpera(
                    "https://cili.site/search?q=${
                        URLEncoder.encode(
                            item.model,
                            Charset.defaultCharset().name()
                        )
                    }"
                )
            }
            openOpera(item.originPage())
            true
        }
    }

    fun openOpera(schemeString : String) {
        val gmmIntentUri = Uri.parse(schemeString)
        val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
        mapIntent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
        mapIntent.setPackage("com.opera.browser")
        lActivity?.startActivity(mapIntent)
    }

    fun  updateData(newList: List<RssDataInterface>) {
        DiffUtil.calculateDiff(RssItemDiffUtil(items, newList)).dispatchUpdatesTo(this)
        items.clear()
        items.addAll(newList)
    }
}

class RssViewHolder(var view: ListItemWithBinding) : RecyclerView.ViewHolder(view.root) {

}

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

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

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

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

//fun View.setOnVeryLongClickListener(listener: () -> Unit) {
//    setOnTouchListener(object : View.OnTouchListener {
//
//        private val longClickDuration = 2000L
//        private val handler = Handler(Looper.getMainLooper())
//
//        override fun onTouch(v: View?, event: MotionEvent?): Boolean {
//            if (event?.action == MotionEvent.ACTION_DOWN) {
//                handler.postDelayed({ listener.invoke() }, longClickDuration)
//            } else if (event?.action == MotionEvent.ACTION_UP) {
//                handler.removeCallbacksAndMessages(null)
//            }
//            return true
//        }
//    })
//}