package ai.pai.lensman.upload;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import ai.pai.lensman.base.BaseInteractor;
import ai.pai.lensman.bean.SessionBean;
import ai.pai.lensman.db.DBService;

public class UploadPresenter implements UploadContract.Presenter,BaseInteractor.InteractorListener<ArrayList<String>> {

    private UploadContract.View uploadView;
    private ArrayList<SessionBean> sessionList;
    private String lensmanId;
    private int sessionSeq;
    private ArrayList<String> sessionIds;
    private FetchSessionIdsInteractor interactor;

    public UploadPresenter(UploadContract.View view,String lensmanId){
        this.uploadView = view;
        this.lensmanId = lensmanId;
        sessionIds = new ArrayList<>();
        interactor = new FetchSessionIdsInteractor(lensmanId,100,this);
    }


    @Override
    public void start() {
        if(sessionIds==null|| sessionIds.size()<20){
            interactor.startJob();
        }
        if(sessionIds==null || sessionIds.size()<1){
            uploadView.setNewSessionBtnEnabled(false);
        }else{
            uploadView.setNewSessionBtnEnabled(true);
        }
        sessionList = DBService.getInstance().getSessionBeanListByDay(getSessionDateInLongFormat());
        if(sessionList.size()==0){
            uploadView.showEmptyView();
        }else{
            uploadView.showSessionViews();
            uploadView.refreshSessionViews(sessionList);
        }
        sessionSeq = sessionList.size();
    }

    @Override
    public void stop() {

    }

    @Override
    public SessionBean createNewSession() {

        SessionBean sessionBean = new SessionBean();
        sessionBean.lensmanId = lensmanId;
        sessionBean.sessionDate=getSessionDateInLongFormat();
        sessionBean.sessionSeq = sessionSeq+1;
        sessionBean.sessionId =sessionIds.get(0);
        sessionList.add(sessionBean);
        sessionIds.remove(0);
        return sessionBean;
    }

    private long getSessionDateInLongFormat(){
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String dateStr = format.format(new Date());
        return Long.parseLong(dateStr);
    }

    @Override
    public void onInteractSuccess(ArrayList<String> sessionIds) {
        this.sessionIds.addAll(sessionIds);
        uploadView.setNewSessionBtnEnabled(true);
    }

    @Override
    public void onInteractFail(String errorMsg) {
//        interactor.startJob();
    }

}
