package ai.pai.lensman.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.android.common.executors.ThreadExecutor;
import com.android.common.utils.LogHelper;

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

public class UploadService extends Service implements UploadTask.OnPhotoUploadListener{

    private PhotoBean currentPhoto;
    private PhotoUploadListener listener;

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent!=null && intent.getSerializableExtra("photo")!=null){
            PhotoBean bean = (PhotoBean) intent.getSerializableExtra("photo");
            bean.uploadStatus = PhotoBean.UploadStatus.STATUS_NO_BEGIN;
            DBService.getInstance().updatePhotoBean(bean);
        }
            startUpload();
        return super.onStartCommand(intent, flags, startId);
    }

    private synchronized void startUpload(){
        if(currentPhoto!=null){
            LogHelper.d("czy","当前有图片正在上传"+currentPhoto);
            return;
        }
         currentPhoto = DBService.getInstance().getNextUploadPhoto();
        if(currentPhoto==null){
            LogHelper.d("czy","本地图片已全部上传");
            return;
        }
        LogHelper.d("czy","即将上传的照片是"+currentPhoto);
        new UploadTask(currentPhoto,this).executeOnExecutor(ThreadExecutor.getInstance().getExecutor());
    }

    @Override
    public void onPhotoUploadSucceed(PhotoBean bean) {
        if(bean.equals(currentPhoto)){
            currentPhoto.uploadStatus =  PhotoBean.UploadStatus.STATUS_SUCCESS;
            DBService.getInstance().updatePhotoBean(currentPhoto);
            if(listener!=null){
                listener.onPhotoUploaded(currentPhoto);
            }
            currentPhoto = null;
        }
        startUpload();
    }

    @Override
    public void onPhotoUploadFail(PhotoBean bean) {
        if(bean.equals(currentPhoto)){
            currentPhoto.uploadStatus =  PhotoBean.UploadStatus.STATUS_ERROR;
            DBService.getInstance().updatePhotoBean(currentPhoto);
            if(listener!=null){
                listener.onPhotoUploadError(currentPhoto);
            }
            currentPhoto = null;
        }
        startUpload();
    }

    public void setPhotoUploadListener(PhotoUploadListener listener){
        this.listener = listener;
    }

    public interface PhotoUploadListener{
        void onPhotoUploaded(PhotoBean bean);
        void onPhotoUploadError(PhotoBean bean);
    }

    public class MyBinder extends Binder {

        public UploadService getService(){
            return UploadService.this;
        }

    }

}
