package bou.amine.apps.readerforselfossv2.android.adapters

import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView.ScaleType
import androidx.recyclerview.widget.RecyclerView
import bou.amine.apps.readerforselfossv2.android.R
import bou.amine.apps.readerforselfossv2.android.databinding.CardItemBinding
import bou.amine.apps.readerforselfossv2.android.model.toTextDrawableString
import bou.amine.apps.readerforselfossv2.android.utils.LinkOnTouchListener
import bou.amine.apps.readerforselfossv2.android.utils.glide.bitmapCenterCrop
import bou.amine.apps.readerforselfossv2.android.utils.glide.circularBitmapDrawable
import bou.amine.apps.readerforselfossv2.android.utils.openInBrowserAsNewTask
import bou.amine.apps.readerforselfossv2.android.utils.openItemUrl
import bou.amine.apps.readerforselfossv2.android.utils.shareLink
import bou.amine.apps.readerforselfossv2.model.SelfossModel
import bou.amine.apps.readerforselfossv2.repository.Repository
import bou.amine.apps.readerforselfossv2.service.AppSettingsService
import bou.amine.apps.readerforselfossv2.utils.getHtmlDecoded
import bou.amine.apps.readerforselfossv2.utils.getIcon
import bou.amine.apps.readerforselfossv2.utils.getThumbnail
import com.amulyakhare.textdrawable.TextDrawable
import com.amulyakhare.textdrawable.util.ColorGenerator
import com.bumptech.glide.Glide
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.kodein.di.DI
import org.kodein.di.android.closestDI
import org.kodein.di.instance

class ItemCardAdapter(
    override val app: Activity,
    override var items: ArrayList<SelfossModel.Item>,
    override val updateItems: (ArrayList<SelfossModel.Item>) -> Unit
) : ItemsAdapter<ItemCardAdapter.ViewHolder>() {
    private val c: Context = app.baseContext
    private val generator: ColorGenerator = ColorGenerator.MATERIAL
    private val imageMaxHeight: Int =
        c.resources.getDimension(R.dimen.card_image_max_height).toInt()

    override val di: DI by closestDI(app)
    override val repository: Repository by instance()
    override val appSettingsService: AppSettingsService by instance()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = CardItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        with(holder) {
            val itm = items[position]

            binding.favButton.isSelected = itm.starred
            binding.title.text = itm.title.getHtmlDecoded()

            binding.title.setOnTouchListener(LinkOnTouchListener())

            binding.title.setLinkTextColor(c.resources.getColor(R.color.colorAccent))

            binding.sourceTitleAndDate.text = itm.sourceAndDateText()

            if (!appSettingsService.isFullHeightCardsEnabled()) {
                binding.itemImage.maxHeight = imageMaxHeight
                binding.itemImage.scaleType = ScaleType.CENTER_CROP
            }

            if (itm.getThumbnail(repository.baseUrl).isEmpty()) {
                binding.itemImage.visibility = View.GONE
                Glide.with(c).clear(binding.itemImage)
                binding.itemImage.setImageDrawable(null)
            } else {
                binding.itemImage.visibility = View.VISIBLE
                c.bitmapCenterCrop(itm.getThumbnail(repository.baseUrl), binding.itemImage)
            }

            if (itm.getIcon(repository.baseUrl).isEmpty()) {
                val color = generator.getColor(itm.title.getHtmlDecoded())

                val drawable =
                    TextDrawable
                        .builder()
                        .round()
                        .build(itm.title.getHtmlDecoded().toTextDrawableString(), color)
                binding.sourceImage.setImageDrawable(drawable)
            } else {
                c.circularBitmapDrawable(itm.getIcon(repository.baseUrl), binding.sourceImage)
            }
        }
    }

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

    inner class ViewHolder(val binding: CardItemBinding) : RecyclerView.ViewHolder(binding.root) {
        init {
            handleClickListeners()
            handleLinkOpening()
        }

        private fun handleClickListeners() {

            binding.favButton.setOnClickListener {
                val item = items[bindingAdapterPosition]
                if (item.starred) {
                    CoroutineScope(Dispatchers.IO).launch {
                        repository.unstarr(item)
                    }
                    binding.favButton.isSelected = false
                } else {
                    CoroutineScope(Dispatchers.IO).launch {
                        repository.starr(item)
                    }
                    binding.favButton.isSelected = true
                }
            }

            binding.shareBtn.setOnClickListener {
                val item = items[bindingAdapterPosition]
                c.shareLink(item.getLinkDecoded(), item.title.getHtmlDecoded())
            }

            binding.browserBtn.setOnClickListener {
                c.openInBrowserAsNewTask(items[bindingAdapterPosition])
            }
        }

        private fun handleLinkOpening() {
            binding.root.setOnClickListener {
                repository.setReaderItems(items)
                c.openItemUrl(
                    bindingAdapterPosition,
                    items[bindingAdapterPosition].getLinkDecoded(),
                    appSettingsService.isArticleViewerEnabled(),
                    app
                )
            }
        }
    }
}
