package ai.pai.lensman.session;

import android.content.Context;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import ai.pai.lensman.bean.PhotoBean;
import ai.pai.lensman.box.ApiClient;
import ai.pai.lensman.db.Preferences;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by chengzhenyu on 2016/7/7.
 */
public class SessionInteractor {

    private Context context;
    private String sessionId;
    private String lensmanId;
    private Timer timer;
    private SessionListener listener;

    public SessionInteractor(Context context,String sessionId, SessionListener listener) {
        this.context = context;
        this.listener = listener;
        this.sessionId = sessionId;
        this.lensmanId = Preferences.getInstance(context).getLensManId();
    }

    public interface SessionListener {

        void onSessionStartSuccess(String session);
        void onSessionStartError(String session);
        void onSessionPhotoCaptured(PhotoBean bean);
        void onSessionEnd(String session);
    }

    public void startSession(){
        ApiClient.service.startNewSession(sessionId,lensmanId).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                listener.onSessionStartSuccess(sessionId);
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                listener.onSessionStartError(sessionId);
            }
        });
    }

    public void startCapture() {
        if(timer!=null){
            timer.cancel();
            timer = null;
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                ApiClient.service.fetchSessionThumbnails(sessionId,lensmanId).enqueue(new Callback<List<PhotoBean>>() {
                    @Override
                    public void onResponse(Call<List<PhotoBean>> call, Response<List<PhotoBean>> response) {

                    }

                    @Override
                    public void onFailure(Call<List<PhotoBean>> call, Throwable t) {

                    }
                });
            }
        },1000,1000);
    }

    public void endSession(){
        if(timer!=null){
            timer.cancel();
            timer = null;
        }
        ApiClient.service.endSession(sessionId,lensmanId).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                listener.onSessionEnd(sessionId);
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

}
