package ai.pai.lensman.session;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;

import com.android.common.utils.LogHelper;

import java.io.File;

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

import static ai.pai.lensman.dslr.CameraService.ACTION_CAMERA_SERVICE_STATUS_CHANGE;
import static ai.pai.lensman.dslr.CameraService.CMD_EXIT_CAMERA_CONNECTION;
import static ai.pai.lensman.dslr.CameraService.CMD_INIT_CAMERA_CONNECTION;
import static ai.pai.lensman.dslr.CameraService.CMD_START_CAPTURE_PHOTO;
import static ai.pai.lensman.dslr.CameraService.EXTRA_CMD;
import static ai.pai.lensman.dslr.CameraService.EXTRA_DATA_PART;
import static ai.pai.lensman.dslr.CameraService.EXTRA_STATUS_PART;
import static ai.pai.lensman.dslr.CameraService.MSG_CAMERA_CONN_ERROR;
import static ai.pai.lensman.dslr.CameraService.MSG_CAMERA_INIT_SUCCESS;
import static ai.pai.lensman.dslr.CameraService.MSG_CAMERA_NEW_PHOTO_FOUND;

public class SessionInteractor implements Callback{

    private Handler mHandler;
    private SessionBean sessionBean;
    private SessionListener listener;
    private String sessionWorkingDirPath;

    private static final int MSG_RETRY_INIT_CAMERA = 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_RETRY_INIT_CAMERA){
            Intent intent = new Intent(App.getAppContext(), CameraService.class);
            intent.putExtra(EXTRA_CMD,CMD_INIT_CAMERA_CONNECTION);
            App.getAppContext().startService(intent);
        }
        return false;
    }

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

    public void startSession(){
        LogHelper.d(TAG,"startSession");
        mHandler = new Handler(this);
        sessionWorkingDirPath = Constants.APP_IMAGE_DIR + File.separator + sessionBean.sessionId
                + File.separator + ai.pai.lensman.utils.Constants.ORIGIN_DIR_NAME;
       new File(sessionWorkingDirPath).mkdirs();
        IntentFilter intentFilter = new IntentFilter(ACTION_CAMERA_SERVICE_STATUS_CHANGE);
        App.getAppContext().registerReceiver(cameraReceiver,intentFilter);
        Intent intent = new Intent(App.getAppContext(), CameraService.class);
        intent.putExtra(EXTRA_CMD,CMD_INIT_CAMERA_CONNECTION);
        App.getAppContext().startService(intent);
    }

    public void startCapture() {
        Intent intent = new Intent(App.getAppContext(), CameraService.class);
        intent.putExtra(EXTRA_CMD,CMD_START_CAPTURE_PHOTO);
        App.getAppContext().startService(intent);
    }


    public void endSession(){
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        Intent intent = new Intent(App.getAppContext(), CameraService.class);
        intent.putExtra(EXTRA_CMD,CMD_EXIT_CAMERA_CONNECTION);
        App.getAppContext().startService(intent);
        App.getAppContext().unregisterReceiver(cameraReceiver);
        LogHelper.d("czy","endSession ");
        listener.onSessionEnd(sessionBean.sessionId);
    }

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

    private BroadcastReceiver cameraReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(!ACTION_CAMERA_SERVICE_STATUS_CHANGE.equals(intent.getAction())){
                return;
            }
            int status = intent.getIntExtra(EXTRA_STATUS_PART,0);
            if(status==MSG_CAMERA_INIT_SUCCESS){
                listener.onSessionStartSuccess(sessionBean.sessionId);
                listener.onCameraStatusChanged("camera init success");
                startCapture();
            }else if(status == MSG_CAMERA_CONN_ERROR){
                listener.onCameraStatusChanged("camera connection error");
                listener.onSessionStartError(sessionBean.sessionId);
                mHandler.sendEmptyMessageDelayed(MSG_RETRY_INIT_CAMERA,3000);
            }else if(status == MSG_CAMERA_NEW_PHOTO_FOUND){
                String eventMsg = intent.getStringExtra(EXTRA_DATA_PART);
                LogHelper.d(TAG,"fetchPhotoTask new photo found");
                listener.onCameraStatusChanged("camera new Photo found "+eventMsg);
                PhotoBean bean = new PhotoBean();
                bean.photoName = eventMsg;
                bean.photoId = Long.parseLong(eventMsg.substring(0,eventMsg.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+eventMsg;
                listener.onSessionPhotoCaptured(bean);
            }

        }
    };

}
