package ai.pai.lensman.session;

import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.TextUtils;

import com.android.common.utils.LogHelper;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import ai.pai.lensman.bean.PhotoBean;
import ai.pai.lensman.bean.SessionBean;
import ai.pai.lensman.dslr.CameraJNIInterface;
import ai.pai.lensman.service.Constants;

public class SessionInteractor implements Callback{

    private Timer photoCaptureTimer;
    private SessionBean sessionBean;
    private SessionListener listener;
    private String sessionWorkingDirPath;

    private boolean isWorking;
    private boolean isLastQueryReturned = true;

    private Handler cameraInitHandler;
    private static final int MSG_CAMERA_INIT_EVENT = 1001;

    private static final String TAG = "SessionInteractor";

    public SessionInteractor(SessionBean sessionBean, SessionListener listener) {
        this.listener = listener;
        this.sessionBean = sessionBean;
    }

    @Override
    public boolean handleMessage(Message message) {
        if(message.what==MSG_CAMERA_INIT_EVENT){
            int result = CameraJNIInterface.getInstance().mygpcamerainit();
            if(result>=0){
                listener.onSessionStartSuccess(sessionBean.sessionId);
                isWorking = true;
                startCapture();
            }else{
                cameraInitHandler.sendEmptyMessageDelayed(MSG_CAMERA_INIT_EVENT,1000);
            }
        }
        return false;
    }

    public interface SessionListener {
        void onSessionStartSuccess(String session);
        void onSessionStartError(String session);
        void onSessionPhotoCaptured(PhotoBean bean);
        void onSessionEnd(String session);
    }

    public void startSession(){
        LogHelper.d(TAG,"startSession");
        sessionWorkingDirPath = Constants.APP_IMAGE_DIR + File.separator + sessionBean.sessionId
                + File.separator + ai.pai.lensman.utils.Constants.ORIGIN_DIR_NAME;
       new File(sessionWorkingDirPath).mkdirs();

        int result = CameraJNIInterface.getInstance().java_mygpcamerainit();
        if(result>=0){
            listener.onSessionStartSuccess(sessionBean.sessionId);
            isWorking = true;
            startCapture();
        }else{
            if(cameraInitHandler!=null){
                cameraInitHandler.removeCallbacksAndMessages(null);
                cameraInitHandler = null;
            }
            cameraInitHandler = new Handler(this);
            cameraInitHandler.sendEmptyMessageDelayed(MSG_CAMERA_INIT_EVENT,1000);
            listener.onSessionStartError(sessionBean.sessionId);
        }

        LogHelper.d(TAG,"startSession sessionStartTask execute");
    }

    public void startCapture() {
        if(photoCaptureTimer !=null){
            photoCaptureTimer.cancel();
            photoCaptureTimer = null;
        }
        photoCaptureTimer = new Timer();
        photoCaptureTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                fetchPhotoTask();
            }
        },2000,1000);
    }

    private void fetchPhotoTask(){
        if(!isWorking){
            return;
        }

        if(!isLastQueryReturned){
            return;
        }

        isLastQueryReturned = false;
        String photoName = CameraJNIInterface.getInstance().java_mygpcamerawaitforevent(sessionWorkingDirPath);
        if(photoName!=null && photoName.length()>0){
            String sub = photoName.substring(0,1);
            if(TextUtils.isDigitsOnly(sub)){
                LogHelper.d(TAG,"fetchPhotoTask new photo found");
                PhotoBean bean = new PhotoBean();
                bean.photoName = photoName;
                bean.photoId = Long.parseLong(photoName.substring(0,photoName.lastIndexOf(".")));
                bean.captureTime = bean.photoId;
                bean.isRawPhoto = true;
                bean.uploadStatus = PhotoBean.UploadStatus.STATUS_NO_BEGIN;
                bean.sessionId = sessionBean.sessionId;
                bean.lensmanId = sessionBean.lensmanId;
                bean.sessionSeq = sessionBean.sessionSeq;
                bean.sessionDate = sessionBean.sessionDate;
                bean.sessionCreateTime = sessionBean.createTime;
                bean.photoPath = sessionWorkingDirPath+File.separator+photoName;
                listener.onSessionPhotoCaptured(bean);
            }
        }

        isLastQueryReturned = true;
    }



    public void endSession(){
        isWorking = false;
        if(photoCaptureTimer !=null){
            photoCaptureTimer.cancel();
            photoCaptureTimer = null;
        }
        CameraJNIInterface.getInstance().java_mygpcameraexit();
        listener.onSessionEnd(sessionBean.sessionId);
        if(cameraInitHandler!=null){
            cameraInitHandler.removeCallbacksAndMessages(null);
            cameraInitHandler = null;
        }
    }

    public void deletePhoto(PhotoBean photoBean){
        LogHelper.d(TAG,"deletePhoto execute "+photoBean);
        new File(photoBean.photoPath).delete();
    }

}
