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

import android.app.Activity
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.utils.LinkOnTouchListener
import bou.amine.apps.readerforselfossv2.android.utils.acra.sendSilentlyWithAcraWithName
import bou.amine.apps.readerforselfossv2.android.utils.glide.bitmapCenterCrop
import bou.amine.apps.readerforselfossv2.android.utils.glide.circularDrawable
import bou.amine.apps.readerforselfossv2.android.utils.openItemUrlInBrowserAsNewTask
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.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 val items: ArrayList<SelfossModel.Item>,
    override val updateHomeItems: (ArrayList<SelfossModel.Item>) -> Unit,
) : ItemsAdapter<ItemCardAdapter.ViewHolder>() {
    override lateinit var binding: CardItemBinding
    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 {
        binding = CardItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    private fun handleClickListeners(holderBinding: CardItemBinding, position: Int) {
        holderBinding.favButton.setOnClickListener {
            val item = items[position]
            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[position]
            c.shareLink(item.getLinkDecoded(), item.title.getHtmlDecoded())
        }

        binding.browserBtn.setOnClickListener {
            c.openItemUrlInBrowserAsNewTask(items[position])
        }
    }

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

            handleClickListeners(binding, position)
            handleLinkOpening(binding, position)

            binding.favButton.isSelected = itm.starred
            if (appSettingsService.getPublicAccess()) {
                binding.favButton.visibility = View.GONE
            }

            binding.title.text = itm.title.getHtmlDecoded()

            binding.title.setOnTouchListener(LinkOnTouchListener())

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

            binding.sourceTitleAndDate.text = try {
                itm.sourceAuthorAndDate()
            } catch (e: Exception) {
                e.sendSilentlyWithAcraWithName("ItemCardAdapter parse date")
                itm.sourceAuthorOnly()
            }

            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()) {
                binding.sourceImage.setBackgroundAndText(itm.sourcetitle.getHtmlDecoded())
            } else {
                c.circularDrawable(itm.getIcon(repository.baseUrl), binding.sourceImage)
            }
        }
    }

    inner class ViewHolder(val binding: CardItemBinding) : RecyclerView.ViewHolder(binding.root)
}