package com.assimilate.alltrans.common

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.UnderlineSpan
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.assimilate.alltrans.R
import com.assimilate.alltrans.model.LanguagesConstants
import com.assimilate.alltrans.model.PreferenceLanguageUtils
import com.assimilate.alltrans.mydb.DbTranslation
import com.assimilate.alltrans.mydb.Translations
import java.util.Locale


object MyTextTools {

    private lateinit var tts: TextToSpeech


    // 分割文本,添加下划线并让其可点击
    fun makeWordsClickableWithUnderline(
        textView: TextView,
        text: String,
        listener: OnWordClickListener?
    ) {
        val spannableStringBuilder = SpannableStringBuilder(text)

        val words = text.split(" ".toRegex()).dropLastWhile { it.isEmpty() }
            .toTypedArray()
        var start = 0

        for (word in words) {
            val end = start + word.length
            spannableStringBuilder.setSpan(object : ClickableSpan() {
                override fun onClick(widget: View) {
                    // Call the listener when the word is clicked
                    listener?.onWordClick(word)
                }

                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.color = Color.BLUE // Change text color on click
                    ds.isUnderlineText = false // Remove default underline
                }
            }, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

            // Apply underline span
            spannableStringBuilder.setSpan(
                UnderlineSpan(),
                start,
                end,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )

            start = end + 1 // Move start position for next word
        }

        textView.text = spannableStringBuilder
        textView.movementMethod = LinkMovementMethod.getInstance() // Enable clicks
    }
    // Interface for click listener
    interface OnWordClickListener {
        fun onWordClick(word: String?)
    }



    // 添加历史
    fun addToHistory(context: Context, rText: String, transResult: String?) {
        val dbTranslation = DbTranslation(context)
        val translations = Translations(
            PreferenceLanguageUtils.getString("language_source"),
            rText,
            PreferenceLanguageUtils.getString("language_target"),
            transResult

        )
        dbTranslation.addTranslation(translations)
    }

    // 分享文本
    fun shareText(context: Context, text: String) {
        val share: String = text.trim()
        if (!TextUtils.isEmpty(share)) {
            val intent = Intent(Intent.ACTION_SEND)
            intent.setType("text/plain")
            intent.putExtra(Intent.EXTRA_TEXT, share)
            context.startActivity(Intent.createChooser(intent, "Share " + R.string.app_name))
        }
    }

    // 复制到粘贴板
    fun copyToClipboard(context: Context, string: String) {
        val tip = "Copied to clipboard!"
        val tipNull = "text is null!"
        val share = string.trim()
        if (!TextUtils.isEmpty(share)) {
            val clipboardManager =
                context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val clipData = ClipData.newPlainText("targetValue", share)
            clipboardManager.setPrimaryClip(clipData)
            Toast.makeText(context, tip, Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(context, tipNull, Toast.LENGTH_SHORT).show()
        }
    }

    // 朗读文本
    fun ttsReadText(text: String, targetLanguage: String, context: Context) {
        Toast.makeText(context, R.string.tr_tts_reading, Toast.LENGTH_SHORT).show()
        tts = TextToSpeech(context) { status ->
            if (TextToSpeech.SUCCESS == status) tts.setLanguage(
                Locale.getDefault()
            )

            tts.setSpeechRate(0.7f)
            val speech: String = text.trim()
            if (!TextUtils.isEmpty(speech)) {
                // 获取目标语言的语言代码
                val languageCode =
                    LanguagesConstants.getInstance()
                        .getLanguageCodeByLanguage(targetLanguage, context)
                Log.d("LanguageCode", "Language Code for $targetLanguage: $languageCode")

                // 创建语言 Locale 对象
                val locale = Locale(languageCode)

                // 判断语言是否支持
                if (TextToSpeech.LANG_NOT_SUPPORTED != tts.isLanguageAvailable(locale)) {
                    tts.language = locale
                    tts.speak(speech, TextToSpeech.QUEUE_FLUSH, null, null)
                } else {
                    Toast.makeText(context, R.string.tr_tts_error, Toast.LENGTH_SHORT).show()
                }

                tts.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
                    override fun onStart(utteranceId: String?) {

                    }

                    override fun onDone(utteranceId: String?) {
                        tts.shutdown()
                    }

                    @Deprecated("Deprecated in Java")
                    override fun onError(utteranceId: String?) {
                        tts.shutdown()
                    }
                })


            }
        }

    }

}