package xyz.r0r5chach.dermy_app

import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jsoup.Jsoup
import org.jsoup.nodes.Document

class LinksAdapter(private val dataSet: Array<String>): RecyclerView.Adapter<LinksAdapter.ViewHolder>() {
    class ViewHolder(view: View): RecyclerView.ViewHolder(view) {
        private val title: TextView = view.findViewById(R.id.link_item_title)

        fun bind(url: String) {
            CoroutineScope(Dispatchers.Main).launch {
                try {
                    updateItem(getInfo(url))
                }
                catch (_: Exception) {
                    updateItem(url)
                }
            }
        }

        private suspend fun getInfo(url: String): Document {
            return withContext(Dispatchers.IO) {
                Jsoup.connect(url).get()
            }
        }

        private fun updateItem(result: Document) {
            title.text = result.title()
            title.setOnClickListener {
                title.context.startActivity(
                    Intent(Intent.ACTION_VIEW, Uri.parse(result.location()))
                )
            }
        }
        private fun updateItem(result: String) {
            title.text = result
            title.setOnClickListener {
                title.context.startActivity(
                    Intent(Intent.ACTION_VIEW, Uri.parse(result))
                )
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.links_list_item, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount() = dataSet.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(dataSet[position])
    }
}
