package com.assimilate.alltrans.common

import android.os.Handler
import android.os.Looper
import android.widget.Toast
import com.assimilate.alltrans.MyApp
import com.assimilate.alltrans.http.GoogleTranslator
import com.assimilate.alltrans.http.Translator
import com.assimilate.alltrans.model.LanguagesConstants
import com.assimilate.alltrans.model.PreferenceLanguageUtils
import com.google.mlkit.vision.text.Text
import java.util.concurrent.Executors

class TranslationManager(
    private val text: Text,
    private val fbFrom: String,
    private val callback: (List<Pair<String, String>>) -> Unit // 修改callback的参数类型
) {
    private val handler = Handler(Looper.getMainLooper())
    private val executor = Executors.newSingleThreadExecutor()
    private var translatedTextBlocks: MutableList<Pair<Int, String>> = mutableListOf()
    private var errorShowed = false


    init {
        prepareTranslation()
    }

    private fun prepareTranslation() {
        executor.execute {
            val lanSourceCode = LanguagesConstants.getInstance().getLanguageCodeByLanguage(
                PreferenceLanguageUtils.getString("language_source"),
                MyApp.applicationContext()
            )
            val lanTargetCode = LanguagesConstants.getInstance().getLanguageCodeByLanguage(
                PreferenceLanguageUtils.getString("language_target"),
                MyApp.applicationContext()
            )

            if (lanTargetCode == null || lanSourceCode == null) {
                println("Language source or target code is null")
                return@execute
            }

            val translator: Translator<GoogleTranslator.GoogleTranslateCallback> =
                GoogleTranslator()

            //根据indices获取对应的文本块将翻译后的文本对应
            for (index in text.textBlocks.indices) {
                // 如果源语言和目标语言相同，直接添加原始文本到 translatedTextBlocks 不请求网络
                if (lanSourceCode == lanTargetCode) {
                    translatedTextBlocks.add(Pair(index, text.textBlocks[index].text))
                    if (translatedTextBlocks.size == text.textBlocks.size) {
                        handler.post {
                            callback(translatedTextBlocks.sortedBy { it.first }
                                .map { it.second to text.textBlocks[it.first].text })
                        }
                    }
                } else {
                    val param = HashMap<String, String>().apply {
                        put("sourceLanguage", lanSourceCode)
                        put("translationLanguage", lanTargetCode)
                        put("text", text.textBlocks[index].text)
                    }

                    translator.translate(param, object : GoogleTranslator.GoogleTranslateCallback {
                        override fun onResponse(result: String?, errorMessage: String?) {
                            handler.post {
                                if (result != null) {
                                    translatedTextBlocks.add(Pair(index, result))
                                } else {
                                    translatedTextBlocks.add(
                                        Pair(
                                            index,
                                            text.textBlocks[index].text
                                        )
                                    )
                                }

                                if (translatedTextBlocks.size == text.textBlocks.size) {
                                    callback(translatedTextBlocks.sortedBy { it.first }
                                        .map { it.second to text.textBlocks[it.first].text })

                                }
                            }
                        }

                        override fun onFailure(errorMessage: String?) {
                            handler.post {
                                translatedTextBlocks.add(Pair(index, text.textBlocks[index].text))
                                if (translatedTextBlocks.size == text.textBlocks.size) {
                                    callback(translatedTextBlocks.sortedBy { it.first }
                                        .map { it.second to text.textBlocks[it.first].text })
                                }

                                if (!errorShowed) {
                                    Toast.makeText(
                                        MyApp.applicationContext(),
                                        errorMessage,
                                        Toast.LENGTH_SHORT
                                    ).show()
                                    transFailEvent(errorMessage)
                                    errorShowed = true
                                }

                            }
                        }
                    })
                }
            }
        }
    }

    private fun transFailEvent(errorMessage: String?) {
        when (fbFrom) {
            "global" -> {
                FirebaseAnalyticsHelper.hoverGlobalResultEvent(
                    MyApp.Config.FAIL_REASON,
                    fbFrom + "_" + errorMessage
                )
            }

            "float" -> {
                FirebaseAnalyticsHelper.hoverGlobalResultEvent(
                    MyApp.Config.FAIL_REASON,
                    fbFrom + "_" + errorMessage
                )
            }

            "photo" -> {
                FirebaseAnalyticsHelper.imagePhotoResultEvent(
                    MyApp.Config.FAIL_REASON,
                    fbFrom + "_" + errorMessage
                )
            }

            "image" -> {
                FirebaseAnalyticsHelper.imageCameraResultEvent(
                    MyApp.Config.FAIL_REASON,
                    fbFrom + "_" + errorMessage
                )
            }
        }
    }
}
