package com.webtoonviewer.utils

import android.text.TextUtils
import android.widget.TextView
import java.nio.file.Paths
import java.util.regex.Pattern

object CommonUtils {
    fun getEpisodeNameFromEpisode(episode: String): String {
        val (_, name) = splitEpisode(episode)
        return name
    }

    fun getShortNameFromEpisode(episode: String): String {
        val pattern = "第(\\d+)話"
        val regex = Regex(pattern)
        var name = getEpisodeNameFromEpisode(episode)

        if (regex.matches(name.split(" ")[0])) {
            name = name.split(" ")[0]
        } else if (name.split(" ").size > 1 && regex.matches(name.split(" ")[1])) {
            name = name.split(" ")[1]
        } else if (name.split(" ")[0].contains("Ep")) {
            name = name.split(" ")[0] + name.split(" ")[name.split(" ").size - 1]
        } else if (name.split(" ").size > 1) {
            name = name.split(" ")[0]
        }
        return name
    }

    fun getEpisodeIndexFromEpisode(episode: String): Int {
        val (index, _) = splitEpisode(episode)
        return index
    }

    private fun splitEpisode(episode: String): Pair<Int, String> {
        val matcher = Pattern.compile("(\\d+)\\.(.+)").matcher(episode)
        var index = 0
        var name = ""
        if (matcher.matches()) {
            index = matcher.group(1)?.toInt() ?: 0
            name = matcher.group(2)?.toString() ?: ""
        }
        return Pair(index, name)
    }

    fun pathJoin(vararg parts: String): String {
        return Paths.get(parts[0], *parts.sliceArray(1 until parts.size)).toString()
    }

    fun getEllipsizedText(textView: TextView, originalText: String): String {
        val availableWidth = textView.width - textView.paddingLeft - textView.paddingRight
        val textPaint = textView.paint

        if (availableWidth > textPaint.measureText(originalText)) {
            return originalText
        } else {
            val parts = originalText.split(" ")
            var maxLength = 0
            var maxIndex = -1
            for ((index, part) in parts.withIndex()) {
                if (part.length > maxLength) {
                    maxIndex = index
                    maxLength = part.length
                }
            }
            val restParts = parts.toMutableList()
            restParts.removeAt(maxIndex)

            val ellipsizedText = TextUtils.ellipsize(
                parts[maxIndex], textPaint,
                (availableWidth - textPaint.measureText(restParts.joinToString(" "))),
                TextUtils.TruncateAt.END).toString()

            return originalText.replace(parts[maxIndex], ellipsizedText)
        }
    }
}