package ai.pai.lensman.session;

import android.os.SystemClock;

import java.util.ArrayList;

import ai.pai.lensman.bean.PhotoBean;
import ai.pai.lensman.bean.SessionBean;
import ai.pai.lensman.db.DBService;

public class SessionPresenter implements SessionContract.Presenter, SessionInteractor.SessionListener {

    private SessionInteractor interactor;
    private ArrayList<PhotoBean> photoList;
    private SessionContract.View sessionView;
    private SessionBean sessionBean;

    public SessionPresenter(SessionBean sessionBean, SessionContract.View view) {
        this.sessionView = view;
        this.sessionBean = sessionBean;
        interactor = new SessionInteractor(sessionBean, this);
    }

    @Override
    public void start() {
        photoList = DBService.getInstance().getPhotoListBySessionId(sessionBean.sessionId);
        //TODO for test
        for (int k = 0; k < 10; k++) {
            PhotoBean bean = new PhotoBean();
            long milisec = System.currentTimeMillis();
            bean.photoName = milisec + ".jpg";
            bean.photoId = milisec;
            bean.photoPath = "http://e.hiphotos.baidu.com/image/h%3D200/sign=31e61d6532f33a87816d071af65d1018/95eef01f3a292df504213240b4315c6035a87381.jpg";
            bean.captureTime = bean.photoId;
            bean.isRawPhoto = false;
            bean.isUploaded = false;
            bean.sessionId = sessionBean.sessionId;
            bean.lensmanId = sessionBean.lensmanId;
            bean.sessionSeq = sessionBean.sessionSeq;
            bean.sessionDate = sessionBean.sessionDate;
            photoList.add(bean);
            SystemClock.sleep(10);
        }
        if (photoList.size() == 0) {
            sessionView.showEmptyView();
        } else {
            sessionView.showPhotoRecyclerView();
            for (PhotoBean photoBean : photoList) {
                sessionView.addNewPhoto(photoBean);
            }
        }
        interactor.startSession();
    }

    @Override
    public void stop() {
        interactor.endSession();
    }

    @Override
    public void onSessionStartSuccess(String session) {
        sessionView.showToast("session启动成功");
    }

    @Override
    public void onSessionStartError(String session) {
        sessionView.showToast("session启动失败");
    }

    @Override
    public void onSessionPhotoCaptured(final PhotoBean bean) {
        DBService.getInstance().addPhotoBean(bean);
        sessionView.showPhotoRecyclerView();
        sessionView.addNewPhoto(bean);
    }

    @Override
    public void onSessionEnd(String session) {

    }

    @Override
    public void swipeToDeletePhoto(int index) {
        PhotoBean photoBean = photoList.get(index);
        photoList.remove(photoBean);
        DBService.getInstance().deletePhotoBean(photoBean);
        interactor.deletePhoto(photoBean);
    }
}
