package ai.pai.lensman.service;

import android.os.AsyncTask;

import com.android.common.utils.LogHelper;

import org.json.JSONObject;

import java.io.File;

import ai.pai.lensman.bean.PhotoBean;
import ai.pai.lensman.db.Preferences;
import ai.pai.lensman.utils.UrlContainer;

public class UploadTask extends AsyncTask<Void, Integer, Boolean> {

    private static final String TAG = "czy";
    private PhotoBean bean;
    private OnPhotoUploadListener listener;

    public UploadTask(PhotoBean bean, OnPhotoUploadListener listener) {
        this.bean = bean;
        this.listener = listener;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        for(int k = 0 ; k< 5;k++){
            try {
                String dirPath = ai.pai.lensman.utils.Constants.APP_IMAGE_DIR + File.separator + bean.sessionId
                        + File.separator + ai.pai.lensman.utils.Constants.THUMBNAIL_DIR_NAME;
                File dir = new File(dirPath);
                dir.mkdirs();
                File photo = new File(dir, bean.photoName);
                LogHelper.d(TAG, "上传照片 第"+k+"次尝试"+ bean);
                if (photo.exists() && photo.isFile()) {
                    PhotoUploadUtils photoUploadUtils = new PhotoUploadUtils(UrlContainer.PHOTO_UPLOAD_URL + "?timestamp=" + System.currentTimeMillis());
                    photoUploadUtils.addFileParameter("photo", photo);
                    photoUploadUtils.addTextParameter("user_id", bean.lensmanId);
                    photoUploadUtils.addTextParameter("session_id", bean.sessionId);
                    photoUploadUtils.addTextParameter("photo_id", String.valueOf(bean.photoId));
                    photoUploadUtils.addTextParameter("nickname",Preferences.getInstance().getUserName());

                    String result = new String(photoUploadUtils.send(), "UTF-8");
                    JSONObject resultObj = new JSONObject(result);
                    if (resultObj.getInt("status") == 200) {
                        LogHelper.d(TAG, "上传 UploadTask upload result ok ");
                        return true;
                    }
                } else {
                    return false;
                }

            } catch (Exception e) {
                LogHelper.d(TAG, "上传发生异常 UploadTask :" + bean + " error:" + e);
            }
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (listener != null) {
            if (result) {
                LogHelper.d(TAG, "上传 UploadTask " + bean + "  success ");
                listener.onPhotoUploadSucceed(bean);
            } else {
                LogHelper.d(TAG, "上传 UploadTask " + bean + "  fail ");
                listener.onPhotoUploadFail(bean);
            }
        }
    }

    public interface OnPhotoUploadListener {
        void onPhotoUploadSucceed(PhotoBean bean);

        void onPhotoUploadFail(PhotoBean bean);
    }
}
