/*
 * 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.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.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.utils.BLog
import java.text.SimpleDateFormat
import java.util.Date


internal class RssItemAdapter (
    private val context: Context) : RecyclerView.Adapter<RssTag>() {
    private var rssDataItemLis: ArrayList<RssDataInterface> = arrayListOf()
    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
    }

    val dateFormat = SimpleDateFormat("a HH:mm / yy - MM - dd")

    @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 = ""
        }

        holder.view.title.text = rssData.title()
        when(rssData.category()) {
            RssDataType.YOUTUBE -> {
                holder.view.desc.text = if(rssData.description().contains("게시자")) rssData.description().split("게시자")[0] else rssData.description()
            }
            RssDataType.NewsFeed -> {
                holder.view.desc.text = rssData.category().name
                holder.view.title.text =  if(rssData.title().length > 30)rssData.title().substring(0,30).plus("...") else rssData.title()
            }
            RssDataType.NO_DATA -> {}
            else -> {
                holder.view.desc.text = rssData.description().plus(" ").plus(rssData.category().name)
            }
        }
        var param = holder.view.circlePreview.layoutParams
        holder.view.circlePreview.layoutParams = ConstraintLayout.LayoutParams(rssData.category().defaultImgSize(), param.height)
        holder.view.circlePreview.visibility = rssData.category().getDefaultVisibiliy()
        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)
            Picasso.get().cancelRequest(holder.view.circlePreview)
        }
        holder.view.root.tag = position
        holder.view.root.setOnClickListener(dateViewClick)
        holder.view.root.setOnLongClickListener(mLongClickListener)
    }

    val dateViewClick  = View.OnClickListener {
        it.findViewById<ShapeableImageView>(R.id.circle_preview)?.let {
            if (it.visibility == View.GONE) {
                it.visibility = View.VISIBLE
                it.postDelayed({
                    it.visibility = View.GONE
                }, 1000L)
            }
        }
    }

    val mLongClickListener = View.OnLongClickListener { v ->
        (v?.tag as? Int)?.let { idx ->
            val rss = rssDataItemLis[idx]
            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
    }

    fun openOpera(schemeString : String) {
        BLog.LOGE("openOpera ${schemeString}")
        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>) {
        try {
            BLog.LOGE("newList >> ${newList}")
            DiffUtil.calculateDiff(RssItemDiffUtil(rssDataItemLis, newList)).apply {

            }.dispatchUpdatesTo(this).apply {
//                notifyItemRangeChanged(0,10)
            }
            rssDataItemLis.clear()
            rssDataItemLis.addAll(newList)
            BLog.LOGE("rssDataItemLis >> ${rssDataItemLis}")
        }catch ( e : Exception) {
            e.printStackTrace()
        }
    }
    fun openNews(schemeString : String) {
        val gmmIntentUri = Uri.parse(schemeString)
        val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
        mapIntent.setPackage("com.android.chrome")
        lActivity?.startActivity(mapIntent)
    }


    fun openYouTube(schemeString : String) {
        val gmmIntentUri = Uri.parse(schemeString)
        val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
        mapIntent.setPackage("com.google.android.youtube")
        lActivity?.startActivity(mapIntent)
    }

    fun openReddit(schemeString : String) {
        val gmmIntentUri = Uri.parse(schemeString)
        val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
        mapIntent.setPackage("com.reddit.frontpage")
        lActivity?.startActivity(mapIntent)
    }

    fun openDotax(schemeString : String) {
        val gmmIntentUri = Uri.parse(schemeString)
        val mapIntent = Intent(Intent.ACTION_VIEW)
        mapIntent.setPackage("net.daum.android.cafe")
        mapIntent.setData(gmmIntentUri)
        lActivity?.startActivity(mapIntent)
    }
}

//fun dp2px(dp: Float): Float {
//    val resources: Resources = this.getResources()
//    val metrics = resources.displayMetrics
//    val px = dp * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
//    return px
//}

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 ""
}
