package ai.pai.lensman.service;

import android.content.Context;
import android.os.AsyncTask;

import com.android.common.utils.LogHelper;
import com.android.common.utils.NetworkUtil;

import org.json.JSONObject;

import java.io.File;

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

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

    private static final String TAG = "czy";
    private Context context;
    private String photoPath;
    private OnPhotoUploadListener listener;
    private String groupId;

    public UploadTask(Context context ,String groupId, OnPhotoUploadListener listener){
        this.context = context;
        this.listener = listener;
        this.groupId = groupId;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        if(!NetworkUtil.isNetworkConnected(context)){
            return false;
        }
        photoPath = params[0];
        try{
            File photo = new File(photoPath);
            LogHelper.d(TAG,"上传照片，路径为 = "+photoPath);
            if(photo.exists() &&photo.isFile()){
                PhotoUploadUtils photoUploadUtils = new PhotoUploadUtils(UrlContainer.HOME_PHOTO_URL+"?timestamp="+System.currentTimeMillis());
                photoUploadUtils.addFileParameter("photo", photo);
                photoUploadUtils.addTextParameter("user_id", Preferences.getInstance(context).getLensManId());
                photoUploadUtils.addTextParameter("group_id", groupId);
                photoUploadUtils.addTextParameter("nickname", Preferences.getInstance(context).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 ");
                    JSONObject info = resultObj.getJSONObject("data");
                    return true;
                }
            }else{
                return false;
            }

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

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

    public interface OnPhotoUploadListener {
        void onPhotoUploadSucceed(String photoPath);
        void onPhotoUploadFail(String photoPath, String groupId);
    }
}
