/*
 * 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.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.net.toUri
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.imageview.ShapeableImageView
import com.squareup.picasso.Picasso
import rasel.lunar.launcher.LauncherActivity.Companion.lActivity
import rasel.lunar.launcher.R
import rasel.lunar.launcher.databinding.ListItemWithBinding
import rasel.lunar.launcher.model.RssDataInterface
import rasel.lunar.launcher.model.RssDataType
import rasel.lunar.launcher.openDotax
import rasel.lunar.launcher.openNews
import rasel.lunar.launcher.openOpera
import rasel.lunar.launcher.openReddit
import rasel.lunar.launcher.openYouTube
import rasel.lunar.launcher.utils.BLog
import java.text.SimpleDateFormat
import java.util.Date

internal class RssItemAdapter (

    private val context: Context) : RecyclerView.Adapter<RssTag>() {
    companion object {
        @SuppressLint("SimpleDateFormat")
        val dateFormat = SimpleDateFormat("a HH:mm / yy - MM - dd")
        val emptyDate = " - "

        val dateViewClick  = View.OnClickListener { v ->
            (v?.tag as? Int)?.let { idx ->
                val rss = rssDataItemLis[idx]
                when(rss.category()) {
                    RssDataType.GURU,RssDataType.Most,RssDataType.REDDIT_nsfw -> {
                        v.findViewById<ShapeableImageView>(R.id.circle_preview)?.let {
                            if (it.visibility == View.GONE) {
                                it.visibility = View.VISIBLE
                                it.postDelayed({
                                    it.visibility = View.GONE
                                }, 2000L)
                            } else {
                                openOpera(rss.originPage())
                            }
                        }
                    }
                    RssDataType.REDDIT -> { openReddit(rss.originPage()) }
                    RssDataType.Dotax -> { openDotax(rss.originPage()) }
                    RssDataType.YOUTUBE -> { openYouTube(rss.originPage()) }
                    else -> { openNews(rss.originPage()) }
                }
            }
        }
        private var rssDataItemLis: ArrayList<RssDataInterface> = arrayListOf()
        val mLongClickListener = View.OnLongClickListener { v ->
            (v?.tag as? Int)?.let { idx ->
                val rss = rssDataItemLis[idx]
                lActivity?.doWebSavor(rss.originPage(),null)
//                when (rss.category()) {
//                    RssDataType.GURU ,RssDataType.Most , RssDataType.TAGS-> { openOpera(rss.originPage()) }
//                    RssDataType.REDDIT -> { openReddit(rss.originPage()) }
//                    RssDataType.Dotax -> { openDotax(rss.originPage()) }
//                    RssDataType.YOUTUBE -> { openYouTube(rss.originPage()) }
//                    else -> { openNews(rss.originPage()) }
//                }
            }
            true
        }
    }



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

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



    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: RssTag, position: Int) {
        val rssData = rssDataItemLis[position]
        if (rssData.pubDate() > 1000L) {
            holder.view.date.text = dateFormat.format(Date(rssData.pubDate()))
        } else {
            holder.view.date.text = emptyDate
        }

        holder.view.title.text = rssData.title()
        holder.view.desc.text = rssData.description()

        var param = holder.view.circlePreview.layoutParams
        holder.view.circlePreview.layoutParams = ConstraintLayout.LayoutParams(rssData.category().defaultImgSize(), param.height)
        holder.view.circlePreview.visibility = rssData.category().getDefaultVisibiliy()
        Picasso.get().cancelRequest(holder.view.circlePreview)

        if(rssData.thumbnailUrl()?.length ?: 0 > 6) {
            Picasso.get().load(rssData.thumbnailUrl().replace("&amp;","&").toUri()).into(holder.view.circlePreview)
        } else if (rssData.category().getResId() > 0 ) {
            holder.view.circlePreview.setImageResource(rssData.category().getResId())
        } else {
            holder.view.circlePreview.setImageDrawable(null)
        }

        holder.view.root.tag = position
        holder.view.root.setOnClickListener(dateViewClick)
        holder.view.root.setOnLongClickListener(mLongClickListener)
    }

    var layoutManager : LinearLayoutManager? = null
    var recyclerView: RecyclerView? = null
    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        layoutManager = recyclerView.layoutManager as? LinearLayoutManager
        this.recyclerView = recyclerView
    }

    fun updateData(newList: List<RssDataInterface>) {
        try {
//            BLog.LOGE("newList >> ${newList}")
            DiffUtil.calculateDiff(RssItemDiffUtil(rssDataItemLis, newList)).apply {

            }.dispatchUpdatesTo(this).apply {
                val visibleItemCount = (layoutManager?.findLastVisibleItemPosition() ?: 0) - (layoutManager?.findFirstVisibleItemPosition() ?: 0)
                if (visibleItemCount > 0) {
                    this@RssItemAdapter.notifyItemRangeChanged(0, visibleItemCount)
                    recyclerView?.scrollToPosition(0)
                }
            }
            rssDataItemLis.clear()
            rssDataItemLis.addAll(newList)
//            BLog.LOGE("rssDataItemLis >> ${rssDataItemLis}")
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

internal class RssTag(var view: ListItemWithBinding) : RecyclerView.ViewHolder(view.root) {}
internal class RssItemDiffUtil(
    var oldList: List<RssDataInterface>, var 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() == if (newList.size > newItemPosition) newList[newItemPosition].originPage() else ""

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
        oldList[oldItemPosition].originPage() == if (newList.size > newItemPosition) newList[newItemPosition].originPage() else ""
}
