package com.example.webapplication.ui.home;

import android.annotation.SuppressLint;
import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.example.webapplication.util.TgUtils;

import java.util.concurrent.TimeUnit;

public class HomeViewModel extends ViewModel {

    private final MutableLiveData<String> mUrl = new MutableLiveData<>();

    public HomeViewModel() {
    }


    public LiveData<String> getUrl() {
        return mUrl;
    }

    public void getMsg() {
        networkListen();
    }

    public void networkListen() {
        ThreadUtils.executeBySingleAtFixRate(new ThreadUtils.Task<String>() {
            @Override
            public String doInBackground() throws Throwable {
                return new TgUtils().getUpdatesSync();
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    SPUtils.getInstance().put("Message", result, true);
                    String url = SPUtils.getInstance().getString("Message");
                    mUrl.postValue(url);
                }
            }

            @Override
            public void onFail(Throwable t) {
                Log.e("hzshkj", "onFail: ", t);
                networkListen();
            }

            @Override
            public void onCancel() {
                networkListen();
            }
        }, 5000, 5000, TimeUnit.MILLISECONDS);

    }
}