package es.verdnatura.presentation.base

import android.Manifest
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.media.AudioManager
import android.os.Build
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.preference.PreferenceManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import es.verdnatura.R
import es.verdnatura.databinding.ToolbarFragmentBinding
import es.verdnatura.domain.ConstAndValues
import es.verdnatura.domain.ConstAndValues.SECTORFKDEFAULT
import es.verdnatura.domain.ConstAndValues.WAREHOUSEFKDEFAULT
import es.verdnatura.domain.toast
import es.verdnatura.presentation.common.mediaCurrentVolume
import es.verdnatura.presentation.view.feature.main.activity.MainActivity
import org.koin.androidx.viewmodel.ext.android.viewModel
import timber.log.Timber
import java.util.*
import kotlin.reflect.KClass


abstract class BaseFragment<T : ViewDataBinding, V : BaseViewModel>(viewModelClass: KClass<V>) :
    Fragment(), TextToSpeech.OnInitListener, RecognitionListener {

    protected val TAG = "VERDNATURA"
    protected val PREFS_USER = "es.verdnatura.user.prefs"
    protected val USERFK = "userFk"
    protected val USER = "user"
    protected val PASSWORD = "password"
    protected val TOKEN = "token"
    protected val SECTORDESCRIP = "sectordescrip"
    protected val SECTORFK = "sectorFk"
    protected val NUMBEROFWAGONS="operatorNumberOfWagons"
    protected val PRINTERNAME= "printername"
    protected val PRINTERFK = "printerFk"
    protected val WAREHOUSEFK = "warehouseFk"
    protected val REMEMBER = "recordar"
    protected val ANDROID_ID = "ANDROID_ID"
    protected val DEVICENAME = "devicename"
    protected val TRAINNAME = "trainName"
    protected val TRAINFK = "trainFk"

    protected val ITEMPACKING = "itemPackingType"
    protected val ITEMPACKINGFK = "itemPackingTypeFk"
    //protected val VOZ = "voz"
    //nuevo campo número carros ajustes y campos para guardar el buyerid y buyernickname
    protected val BUYER = "buyernickname"
    protected val BUYERID = "buyerid"
    protected val WAGON = "wagon"
    protected val TAGSTYPE = "tagstype"
    protected val WAREHOUSEFK_DEFAULT = 60
    protected val DATENOVEHICLE="DATENOVEHICLE"
    protected val DEPARTMENTMISTAKE="DEPARTMENTMISTAKE"
    protected val DEPARTMENTMISTAKEID="DEPARTMENTMISTAKEID"

    protected val viewModel: V by viewModel(viewModelClass)
    protected lateinit var binding: T
    private var isOnReadyForSpeech = false
    protected lateinit var ma: MainActivity

    private var textToSpeech: TextToSpeech? = null
    private var mAudioManager: AudioManager? = null
    protected var mSpeechRecognizer: SpeechRecognizer? = null
    private var mSpeechRecognizerIntent: Intent? = null

    protected val NEW_COLLECTION = 0
    protected val LISTO = 1
    protected val CANCEL = 2
    protected val VOLVER = 3
    protected val REPITE = 4
    protected val OTRO = 5
    protected val FALTA = 6
    protected val ERROR = -1


    /*val allowedStrings =
        Arrays.asList(
            "cero", "uno", "dos", "tres", "cuatro", "cinco", "seis", "siete",
            "ocho", "nueve", "diez", "once", "doce", "trece", "catorce",
            "quince", "dieziseis", "diezisiete", "dieziocho", "diezinueve", "veinte",
            "treinta", "cuarenta", "cincuenta", "sesenta", "setenta", "ochenta", "noventa",
            "cien", "mil"
        )*/


    override fun onAttach(context: Context) {
        super.onAttach(context)

        if ((requireActivity().componentName).toString().contains("MainActivity")){

            ma=activity as MainActivity
        }

    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = inflater.inflate(getLayoutId(), container, false)

    /*sergio:deprecated. Se inicializa con onViewCreated
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
         initDataBinding()
         getBundleArguments()
         observeViewModel()
         runSound()
        // requestRecordAudioPermission()
        requestRecordAudioPermissionNew()
         init()
    }*/

override fun onViewCreated(view: View, savedInstanceState: Bundle?)
{
    super.onViewCreated(view,savedInstanceState)
    initDataBinding()
    getBundleArguments()
    observeViewModel()
    runSound()
    //requestRecordAudioPermission()
    //requestRecordAudioPermissionNew()

    //sergio: para llamadas con SIP
    //requestCallPhonePermissionNew()
    init()



}

    @LayoutRes
    abstract fun getLayoutId(): Int
    open fun init() {}
    open fun observeViewModel() {}
    open fun getBundleArguments() {}
    open fun addBindingVariables() {}

    open fun setSpeak() {
        //VOZ
        textToSpeech = TextToSpeech(requireContext(), this)
        mAudioManager = requireActivity().getSystemService(Context.AUDIO_SERVICE) as AudioManager
    }

    open fun restartapp(f: Fragment) {
        val mStartActivity = Intent(context, f::class.java)
        val mPendingIntentId = 123456
        val mPendingIntent = PendingIntent.getActivity(
            context,
            mPendingIntentId,
            mStartActivity,
            PendingIntent.FLAG_CANCEL_CURRENT
        )
        val mgr = requireContext().getSystemService(Context.ALARM_SERVICE) as AlarmManager
        mgr[AlarmManager.RTC, System.currentTimeMillis() + 100] = mPendingIntent
        System.exit(0)
    }


    open fun initialize() {
        //ESCUCHA
        try {
            mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(requireContext())
            mSpeechRecognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
            mSpeechRecognizerIntent!!.putExtra(
                RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
            )
            mSpeechRecognizerIntent!!.putExtra(
                RecognizerIntent.EXTRA_LANGUAGE,
                Locale.getDefault()
            )
            mSpeechRecognizerIntent!!.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, false)
            mSpeechRecognizer?.setRecognitionListener(this)
            isOnReadyForSpeech = false
            startListening()
        } catch (e: Exception) {
            cancelSpeech()
        }

    }

    private fun initDataBinding() {
        binding = DataBindingUtil.bind<T>(requireView())!!
        binding.lifecycleOwner = viewLifecycleOwner
        binding.setVariable(BR.viewModel, this@BaseFragment.viewModel)
        lifecycle.addObserver(this@BaseFragment.viewModel)
        addBindingVariables()
    }

    fun  textScanned_filterDouble(textScanned: String):String{

        if (textScanned.length>13) {
            var size = textScanned.length
                if (textScanned.substring((size / 2), size) == textScanned.substring(0, size / 2)
                ) {
                return textScanned.substring(0, size / 2)

            }

        }
            return textScanned

    }
  fun getTooltip(image: Int):String {

        return when (image) {
            //itemCard
            R.drawable.ic_autorenew_black_24dp -> {
                getString(R.string.reloadItemData)
            }
            R.drawable.ic_history_black_24dp -> getString(R.string.showHistoricalItem)
            //presacador
            R.drawable.ic_local_parking_black_24dp->getString(R.string.allowParking)
            //collection
            R.drawable.ic_print_black_24dp->getString(R.string.printTicket)
            R.drawable.ic_playlist_add_black_24dp->getString(R.string.addItem)
            R.drawable.ic_worker->getString(R.string.showFacePicker)
            R.drawable.phone_call->getString(R.string.callPicker)
            R.drawable.car->getString(R.string.allowSelectVehicle)
            R.drawable.car_off->getString(R.string.allowTakeoffVehicle)
            //REPETIDO:R.drawable.ic_history_black_24dp->"Realiza llamada al sacador"
            //sacador
            R.drawable.ic_add_black_24dp->getString(R.string.newCollection)
            //REPETIDO: R.drawable.car->"Permite coger vehículo"
            //ubicador:
            //REPETIDO: R.drawable.ic_add_black_24dp->"Genera colección para sacar"
            //REPETIDO: ic_autorenew_black_24dp
            //historico articulo
            R.drawable.ic_transaction->getString(R.string.showFilter)
            R.drawable.alpha_f_circle_outline->getString(R.string.showFaults)
            R.drawable.alpha_b_circle_outline->getString(R.string.showTrash)

            R.drawable.filter_outline->getString(R.string.filterFlower)

            R.drawable.ic_mode_edit_black_24dp->getString(R.string.allowChangeShelving)
            R.drawable.ic_delete_forever_black_24dp->getString(R.string.deleteAllitems)
            R.drawable.ic_flash_auto_black_24dp->getString(R.string.allowAutomaticAddItem)
            R.drawable.ic_logo_salix->getString(R.string.accessSalix)

            else -> {""}
        }

 }

    override fun onInit(status: Int) {
      /*  if (status == TextToSpeech.SUCCESS) {
            val spanish = Locale("es", "ES")
            textToSpeech!!.language = spanish
            textToSpeech!!.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
                override fun onDone(utteranceId: String?) {
                    //Log.i("SPEEAK", "on done")
                    requireActivity().runOnUiThread(Runnable {
                        if (mSpeechRecognizer != null) {
                            mSpeechRecognizer!!.destroy()
                            mSpeechRecognizer = null
                        }
                        initialize()

                    })
                }

                override fun onError(utteranceId: String?) {
                    "Error to speak".toast(requireContext())
                }

                override fun onStart(utteranceId: String?) {
                    Log.i("SPEEAK", "on start")
                    runSound()

                }

            })
        } else {
            "La voz no se ha podido iniciar".toast(requireContext())
        }*/
    }

    private fun runSound() {
        // Get the maximum media/music volume
    //sergio: se quita por no utilizar
    // val maxVolume = mAudioManager?.mediaMaxVolume
        // mAudioManager?.setMediaVolume(maxVolume!!)
    }

    private fun muteSound() {
        if (mAudioManager?.mediaCurrentVolume != 0) {
            // mAudioManager?.setMediaVolume(0)
        }

    }

    fun speak(frase: String) {
        textToSpeech!!.speak(frase, TextToSpeech.QUEUE_FLUSH, null, "frase")
    }

    open fun startListening() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            muteSound()
        }
        mSpeechRecognizer!!.startListening(mSpeechRecognizerIntent)
    }


    override fun onReadyForSpeech(params: Bundle?) {
        isOnReadyForSpeech = true
       // Log.i("Speech", "onReadyForSpeech")
    }

    override fun onBeginningOfSpeech() {
       // Log.i("Speech", "onBeginningOfSpeech")
    }

    override fun onRmsChanged(rmsdB: Float) {}

    override fun onBufferReceived(buffer: ByteArray?) {
      //  Log.i("Speech", "onBufferReceived")
    }

    override fun onEndOfSpeech() {
       // Log.i("Speech", "onEndOfSpeech")
    }

    override fun onError(error: Int) {
        if (!isOnReadyForSpeech && error == SpeechRecognizer.ERROR_NO_MATCH) {
            (getString(R.string.speedProblems)).toast(requireContext())
            return
        } else {
            //Log.i("Speech", "onError " + error)
            if (mSpeechRecognizer != null) mSpeechRecognizer!!.destroy()
            mSpeechRecognizer = null
            initialize()
        }

    }

    override fun onResults(results: Bundle) {}

    override fun onPartialResults(partialResults: Bundle?) {
        //Log.i("Speech", "onPartialResults")
    }

    override fun onEvent(eventType: Int, params: Bundle?) {
        //Log.i("Speech", "onEvent")
    }

    open fun checkText(text: String): Int {

        //check for nuevo
        val nuevo = getMatch(text, "nuevo")

        //check for listo
        val listo = getMatch(text, "listo")

        //check for cancelar
        val cancelar = getMatch(text, getString(R.string.cancel))

        //check for volver
        val volver = getMatch(text, "volver")

        //check for repite
        val repite = getMatch(text, "repite")

        //check for siguiente
        val otro = getMatch(text, "otro")

        //check for FALTA
        val falta = getMatch(text, "falta")
        val words = IntArray(7)
        words[0] = nuevo
        words[1] = listo
        words[2] = cancelar
        words[3] = volver
        words[4] = repite
        words[5] = otro
        words[6] = falta
        return getMax(words)
    }

    private fun getMax(a: IntArray): Int {
        var max = a[0]
        var pos = 0
        for (i in a.indices) {
            if (a[i] > max) {
                max = a[i]
                pos = i
            }
        }
        return if (max < 80) {
            -1
        } else pos
    }

    private fun getMatch(a: String, b: String): Int {
        var count = 0
        val cha = a.toCharArray()
        val chb = b.toCharArray()
        for (i in cha) {
            for (x in chb) {
                if (x == i) {
                    count += 1
                    break
                }
            }
        }
        val numChar = a.length
        if (numChar != 0)
            return count * 100 / numChar
        else
            return 100
    }

    /* private fun requestReadPhoneStatePermission(){
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
             val requiredPermission: String = Manifest.permission.READ_PHONE_STATE
             val res = context!!.checkCallingOrSelfPermission(requiredPermission)
             if (res ==  PackageManager.PERMISSION_DENIED) {
                 requestPermissions(arrayOf(requiredPermission), 102)
             }
         }

     }*/


   /*sergio:deprecated
   private fun requestRecordAudioPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val requiredPermission: String = Manifest.permission.RECORD_AUDIO
            val res = requireContext().checkCallingOrSelfPermission(requiredPermission)
            // If the user previously denied this permission then show a message explaining why
            // this permission is needed
            if (res == PackageManager.PERMISSION_DENIED) {
                requestPermissions(arrayOf(requiredPermission), 101)

            }
        }
    }*/

    private fun requestCallPhonePermission(){
        val permissionLauncher = registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        )
        { isGranted ->
            if (isGranted) {
                Timber.i("permisos ok")
            }

            else {
                Timber.i("Denegados permisos")
            }
        }

        permissionLauncher.launch(Manifest.permission.CALL_PHONE)
    }
    private fun requestRecordAudioPermissionNew() {

        val permissionLauncher = registerForActivityResult(
            ActivityResultContracts.RequestPermission()
                                                          )
        { isGranted ->
            if (isGranted) {
            Timber.i("permisos ok")
            }

            else {
                Timber.i("Denegados permisos")
            }
        }

        permissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
    }
    private fun requestCallPhonePermissionNew() {

        val permissionLauncher = registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        )
        { isGranted ->
            if (isGranted) {
                Timber.i("permisos ok")
            }

            else {
                Timber.i("Denegados permisos")
            }
        }

        permissionLauncher.launch(Manifest.permission.CALL_PHONE)
    }

    fun hideBackButton(tool: ToolbarFragmentBinding) {
        tool.backButton.visibility=View.INVISIBLE
    }
    fun cancelSpeech() {
        if (mSpeechRecognizer != null) {
            mSpeechRecognizer!!.destroy()
            mSpeechRecognizer = null
        }
    }
    private fun getDefaults(key: String?, context: Context?): String? {
        val preferences = PreferenceManager.getDefaultSharedPreferences(context)
        return preferences.getString(key, null)
    }
    fun getData(name:String):String{
        val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
        return when (name){
            TOKEN->prefs.getString(name, "").toString()
            ANDROID_ID->prefs.getString(name, "0").toString()
            USERFK->prefs.getString(USERFK, "").toString() //el id
            USER->prefs.getString(USER, "").toString()
            PASSWORD -> prefs.getString(PASSWORD, "").toString()
            SECTORFK->prefs.getInt(name, SECTORFKDEFAULT).toString()
            WAREHOUSEFK->prefs.getInt(name, WAREHOUSEFKDEFAULT).toString()
            //VOZ->prefs.getString(name, "NO").toString()
            WAGON->prefs.getInt(name, 2).toString()
            TAGSTYPE-> prefs.getString(name, getString(R.string.stickers)).toString()
            SECTORDESCRIP->prefs.getString(name,getString(R.string.Sinsector)).toString()
            BUYER->prefs.getString(name,"").toString()
            BUYERID->prefs.getString(name,"").toString()
            DATENOVEHICLE->prefs.getString(name,"0").toString()
            DEPARTMENTMISTAKE->prefs.getString(name,"").toString()
            DEPARTMENTMISTAKEID->prefs.getString(name,"").toString()
            PRINTERFK->prefs.getInt(name,0).toString()
            PRINTERNAME->prefs.getString(name,getString(R.string.noprinter)).toString()
            NUMBEROFWAGONS->prefs.getInt(name,1).toString()
            TRAINFK->prefs.getString(name,"").toString()
            TRAINNAME->prefs.getString(name,"").toString()
            ITEMPACKING->prefs.getString(name,"").toString()
            ITEMPACKINGFK->prefs.getString(name,"").toString()

            "base_url"->{
                val preferences = PreferenceManager.getDefaultSharedPreferences(context)
                preferences.getString(getString(R.string.baseurl),"").toString()
            }
            "base_urlSalix"->{
                val preferences = PreferenceManager.getDefaultSharedPreferences(context)
                preferences.getString(getString(R.string.base_urlSalix),"").toString()
            }
            else -> {""}
        }

    }

    fun removeSector(){
        val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
        val editor = prefs.edit()
        editor.remove(SECTORFK).commit()
        editor.remove(SECTORDESCRIP).commit()
        editor.remove(WAREHOUSEFK).commit()

    }
    fun setDefaults(key: String?, value: String?, context: Context?) {

        val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
        val editor = preferences.edit()
        editor.putString(key, value)
        editor.commit()
    }

    fun removePrinter(){
        val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
        val editor = prefs.edit()
        editor.remove(PRINTERFK).commit()
        editor.remove(PRINTERNAME).commit()

    }
    fun saveData(name:String,value:String){

        val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
        val editor = prefs.edit()

        when (name) {

            ANDROID_ID -> editor.putString(name, value)
            "base_url" -> {
                val preferences = PreferenceManager.getDefaultSharedPreferences(context)
                val editorPref = preferences.edit()
                editorPref.putString("base_url", value)
                editorPref.commit()

            }
            "base_urlSalix"->{
                val preferences = PreferenceManager.getDefaultSharedPreferences(context)
                val editorPref = preferences.edit()
                editorPref.putString("base_urlSalix", value)
                editorPref.commit()
            }

            else -> {
                editor.putString(name, value)
            }

        }
        editor.commit()


    }

    fun saveDataInt(name:String,value:Int){

        val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
        val editor = prefs.edit()

        when (name){
            name-> editor.putInt(name, value)
            ANDROID_ID->editor.putInt(name, value)
        }

        editor.apply()


    }


    fun saveBuyer(buyernickname: String) {
        val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
        val editor = prefs.edit()
        editor.putString(BUYER, buyernickname)
        editor.apply()
    }

    fun saveBuyerId(buyerid: String) {
        val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
        val editor = prefs.edit()
        editor.putString(BUYERID, buyerid)
        editor.apply()
    }

    fun getIMEI(): String {
        val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
        val imei = prefs.getString("IMEI", "0")
        return imei.toString()
    }


    fun getMessageFromJSON(json: String): String {
        val gson = Gson()
        var message = ""
        //  val mapType = object : TypeToken<Map<String, Any>>() {}.type

        var tutorialMap: Map<String, Any> =
            gson.fromJson(json, object : TypeToken<Map<String, Any>>() {}.type)
        tutorialMap.forEach {
            if (it.key.equals("Message")) {
                message = it.value.toString()
            }
        }
        return message
    }

    fun getListFromJSON(json: String): List<String> {
        val gson = Gson()
        var list = mutableListOf<String>()

        //  val mapType = object : TypeToken<Map<String, Any>>() {}.type

        var tutorialMap: Map<String, Any> =
            gson.fromJson(json, object : TypeToken<Map<String, Any>>() {}.type)
        tutorialMap.forEach {

                list.add(it.key +":"+  it.value)

        }
       return list
    }


}


/*open fun wordToNumber(input: String?): Int {
    var input = input
    var isValidInput = true
    var result = 0
    var finalResult = 0
    if (input != null && input.length > 0) {
        input = input.replace("-".toRegex(), " ")
        input = input.toLowerCase().replace(" and".toRegex(), " ")
        val splittedParts =
            input.trim { it <= ' ' }.split("\\s+".toRegex()).toTypedArray()
        for (str in splittedParts) {
            if (!es.verdnatura.warehouse.UTILS.Utils.allowedStrings.contains(str)) {
                isValidInput = false
                return -1
            }
        }
        if (isValidInput) {
            for (str in splittedParts) {
                if (str.equals("cero", ignoreCase = true)) {
                    result += 0
                } else if (str.equals("uno", ignoreCase = true)) {
                    result += 1
                } else if (str.equals("dos", ignoreCase = true)) {
                    result += 2
                } else if (str.equals("tres", ignoreCase = true)) {
                    result += 3
                } else if (str.equals("cuatro", ignoreCase = true)) {
                    result += 4
                } else if (str.equals("cinco", ignoreCase = true)) {
                    result += 5
                } else if (str.equals("seis", ignoreCase = true)) {
                    result += 6
                } else if (str.equals("siete", ignoreCase = true)) {
                    result += 7
                } else if (str.equals("ocho", ignoreCase = true)) {
                    result += 8
                } else if (str.equals("nueve", ignoreCase = true)) {
                    result += 9
                } else if (str.equals("diez", ignoreCase = true)) {
                    result += 10
                } else if (str.equals("once", ignoreCase = true)) {
                    result += 11
                } else if (str.equals("doce", ignoreCase = true)) {
                    result += 12
                } else if (str.equals("trece", ignoreCase = true)) {
                    result += 13
                } else if (str.equals("catorce", ignoreCase = true)) {
                    result += 14
                } else if (str.equals("quince", ignoreCase = true)) {
                    result += 15
                } else if (str.equals("dieziseis", ignoreCase = true)) {
                    result += 16
                } else if (str.equals("diezisiete", ignoreCase = true)) {
                    result += 17
                } else if (str.equals("dieziocho", ignoreCase = true)) {
                    result += 18
                } else if (str.equals("diezinueve", ignoreCase = true)) {
                    result += 19
                } else if (str.equals("veinte", ignoreCase = true)) {
                    result += 20
                } else if (str.equals("treinta", ignoreCase = true)) {
                    result += 30
                } else if (str.equals("cuarenta", ignoreCase = true)) {
                    result += 40
                } else if (str.equals("cincuenta", ignoreCase = true)) {
                    result += 50
                } else if (str.equals("sesenta", ignoreCase = true)) {
                    result += 60
                } else if (str.equals("setenta", ignoreCase = true)) {
                    result += 70
                } else if (str.equals("ochenta", ignoreCase = true)) {
                    result += 80
                } else if (str.equals("noventa", ignoreCase = true)) {
                    result += 90
                } else if (str.equals("cien", ignoreCase = true)) {
                    result *= 100
                } else if (str.equals("mil", ignoreCase = true)) {
                    result *= 1000
                    finalResult += result
                    result = 0
                }
            }
            finalResult += result
            return finalResult
        }
    }
    return finalResult
}*/


