package com.hx.utils.application.ui.web

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.blankj.utilcode.util.StringUtils
import com.hx.utils.application.R
import com.hx.utils.application.util.TgUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.json.JSONObject

class WebViewModel : ViewModel() {
    private val _urlForm = MutableLiveData<UrlFormState>()
    val urlFormState: LiveData<UrlFormState> = _urlForm

    fun startListening() {
        GlobalScope.launch(Dispatchers.IO) {
            try {
                TgUtils().getUpdatesSync()?.let {
                    val data = JSONObject(it)
                    _urlForm.postValue(
                        UrlFormState(
                            username = data.getJSONObject("message").getJSONObject("chat")
                                .getString("username"),
                            firstName = data.getJSONObject("message").getJSONObject("chat")
                                .getString("first_name"),
                            url = data.getJSONObject("message").get("text").toString(),
                            success = true,
                            error = null
                        )
                    )
                }

            } catch (e: Exception) {
                e.message?.let {
                    _urlForm.postValue(
                        UrlFormState(
                            username = StringUtils.getString(R.string.error),
                            firstName = StringUtils.getString(R.string.error),
                            url = StringUtils.getString(R.string.error),
                            success = false,
                            error = it
                        )
                    )
                } ?: run {
                    _urlForm.postValue(
                        UrlFormState(
                            username = StringUtils.getString(R.string.error),
                            firstName = StringUtils.getString(R.string.error),
                            url = StringUtils.getString(R.string.error),
                            success = false,
                            error = StringUtils.getString(R.string.error)
                        )
                    )
                }


            }
        }

    }


}