package ai.pai.lensman.briefs;

import com.android.common.utils.NetworkUtil;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import ai.pai.lensman.App;
import ai.pai.lensman.base.BaseInteractor;
import ai.pai.lensman.bean.BriefsBean;

public class BriefsPresenter implements BriefsContract.Presenter,BaseInteractor.InteractorListener<BriefsBean> {

    private BriefsContract.View briefsView;
    private BriefsInteractor interactor;
    private BriefsBean briefsBean;
    private String NULL_STR = "";
    private Timer timer;

    public BriefsPresenter(BriefsContract.View briefsView){
        this.briefsView = briefsView;
        interactor = new BriefsInteractor(this);
    }

    @Override
    public void start() {
        interactor.startJob();
    }

    @Override
    public void stop() {
        interactor.cancelJob();
        if(timer!=null){
            timer.cancel();
        }
    }

    @Override
    public void onInteractSuccess(BriefsBean bean) {
        this.briefsBean = bean;
        briefsView.updateUserInfo(bean);
        briefsView.updateMessageBar(getNextSystemMessage(),getNextOrderMessage());
        if(timer!=null){
            timer.cancel();
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                briefsView.updateMessageBar(getNextSystemMessage(),getNextOrderMessage());
            }
        },1000,3000);
    }

    @Override
    public void onInteractFail(String errorMsg) {
        if(NetworkUtil.isWifiConnected(App.getAppContext())){
            interactor.startJob();
        }
    }

    private String getNextOrderMessage(){
        if(briefsBean == null || briefsBean.msgList==null || briefsBean.msgList.size()==0){
            return NULL_STR;
        }
        return briefsBean.msgList.get(new Random().nextInt(briefsBean.msgList.size())).content;
    }

    private String getNextSystemMessage(){
        if(briefsBean == null || briefsBean.systemMsgList==null || briefsBean.systemMsgList.size()==0){
            return NULL_STR;
        }
        return briefsBean.systemMsgList.get(new Random().nextInt(briefsBean.systemMsgList.size())).content;
    }

}
