package bou.amine.apps.readerforselfossv2.android.utils

import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.Spannable
import android.text.style.ClickableSpan
import android.util.Patterns
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import android.widget.Toast
import bou.amine.apps.readerforselfossv2.android.R
import bou.amine.apps.readerforselfossv2.android.ReaderActivity
import bou.amine.apps.readerforselfossv2.model.SelfossModel
import bou.amine.apps.readerforselfossv2.utils.toStringUriWithHttp
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull


fun Context.openItemUrl(
    currentItem: Int,
    linkDecoded: String,
    articleViewer: Boolean,
    app: Activity,
) {
    if (!linkDecoded.isUrlValid()) {
        Toast.makeText(
            this,
            this.getString(R.string.cant_open_invalid_url),
            Toast.LENGTH_LONG,
        ).show()
    } else {
        if (articleViewer) {
            val intent = Intent(this, ReaderActivity::class.java)
            intent.putExtra("currentItem", currentItem)
            app.startActivity(intent)
        } else {
            this.openUrlInBrowserAsNewTask(linkDecoded)
        }
    }
}

fun String.isUrlValid(): Boolean =
    this.toHttpUrlOrNull() != null && Patterns.WEB_URL.matcher(this).matches()

fun String.isBaseUrlInvalid(): Boolean {
    val baseUrl = this.toHttpUrlOrNull()
    var existsAndEndsWithSlash = false
    if (baseUrl != null) {
        val pathSegments = baseUrl.pathSegments
        existsAndEndsWithSlash = "" == pathSegments[pathSegments.size - 1]
    }

    return !(Patterns.WEB_URL.matcher(this).matches() && existsAndEndsWithSlash)
}

fun Context.openItemUrlInBrowserAsNewTask(i: SelfossModel.Item) {
    this.openUrlInBrowserAsNewTask(i.getLinkDecoded().toStringUriWithHttp())
}

fun Context.openUrlInBrowserAsNewTask(url: String) {

    val intent = Intent(Intent.ACTION_VIEW)
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    intent.data = Uri.parse(url)
    this.mayBeStartActivity(intent)
}

fun Context.openUrlInBrowser(url: String) {
    val intent = Intent(Intent.ACTION_VIEW)
    intent.data = Uri.parse(url)
    this.mayBeStartActivity(intent)
}

fun Context.mayBeStartActivity(intent: Intent) {
    try {
        this.startActivity(intent)
    } catch (e: ActivityNotFoundException) {
        Toast.makeText(this, getString(R.string.no_browser), Toast.LENGTH_SHORT).show()
    }

}

class LinkOnTouchListener : View.OnTouchListener {
    override fun onTouch(
        v: View?,
        event: MotionEvent?,
    ): Boolean {
        var ret = false
        val widget: TextView = v as TextView
        val text: CharSequence = widget.text
        val stext = Spannable.Factory.getInstance().newSpannable(text)

        val action = event!!.action

        if (action == MotionEvent.ACTION_UP ||
            action == MotionEvent.ACTION_DOWN
        ) {
            var x: Float = event.x
            var y: Float = event.y

            x -= widget.totalPaddingLeft
            y -= widget.totalPaddingTop

            x += widget.scrollX
            y += widget.scrollY

            val layout = widget.layout
            val line = layout.getLineForVertical(y.toInt())
            val off = layout.getOffsetForHorizontal(line, x)

            val link = stext.getSpans(off, off, ClickableSpan::class.java)

            if (link.isNotEmpty()) {
                if (action == MotionEvent.ACTION_UP) {
                    link[0].onClick(widget)
                }
                ret = true
            }
        }
        return ret
    }
}