package com.example.webapplication.ui.notifications;

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

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

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

import java.util.concurrent.TimeUnit;

public class NotificationsViewModel extends ViewModel {

    private final MutableLiveData<Boolean> success = new MutableLiveData<>();

    public MutableLiveData<String> getError() {
        return error;
    }

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


    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) {
                Log.d("hzshkj", "[NotificationsViewModel] onSuccess: "+result);
                error.postValue(result);
                success.postValue(true);
            }

            @Override
            public void onFail(Throwable t) {
                Log.d("hzshkj", "[NotificationsViewModel] onFail: "+t.getMessage());
                success.postValue(false);
                error.postValue(t.getMessage());
                networkListen();
            }

            @Override
            public void onCancel() {
                success.postValue(false);
                error.postValue("Task is cancel.");
                networkListen();
            }
        }, 100, 10000, TimeUnit.MILLISECONDS);

    }

    public MutableLiveData<Boolean> getSuccess() {
        return success;
    }
}