package ai.pai.client.services;

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

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

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import ai.pai.client.beans.GroupPhotoItem;
import ai.pai.client.db.DBService;
import ai.pai.client.db.Preferences;
import ai.pai.client.utils.PhotoUploadUtils;
import ai.pai.client.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 ArrayList<GroupPhotoItem> photoItems;
    private String groupId;
    private String currentPhotoId;

    public UploadTask(Context context ,String groupId, OnPhotoUploadListener listener){
        this.context = context;
        this.listener = listener;
        this.groupId = groupId;
        this.currentPhotoId = String.valueOf(DBService.getInstance(context).getCurrentIdByGroupId(groupId));
        photoItems = new ArrayList<GroupPhotoItem>();
    }

    @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.GROUP_UPLOAD_PHOTO_URL+"?timestamp="+System.currentTimeMillis());
                photoUploadUtils.addFileParameter("photo", photo);
                photoUploadUtils.addTextParameter("user_id", Preferences.getInstance(context).getUserId());
                photoUploadUtils.addTextParameter("group_id", groupId);
                photoUploadUtils.addTextParameter("nickname", Preferences.getInstance(context).getUserName());
                photoUploadUtils.addTextParameter("current_id", currentPhotoId);
                LogHelper.d(TAG,"上传 UploadTask with local currentId = "+currentPhotoId);
                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");
                    JSONArray photoArray = info.getJSONArray("photos");
                    if(photoArray!=null && photoArray.length()>0){
                        for(int k = 0; k<photoArray.length();k++){
                            JSONObject photoObj = photoArray.getJSONObject(k);
                            photoItems.add(GroupPhotoItem.parseFromJSON(photoObj));
                        }
                        LogHelper.d(TAG,"上传 UploadTask new photos added,size: "+photoItems.size());
                        DBService.getInstance(context).addGroupPhotoList(photoItems);
                    }
                    int currentId = info.getInt("current_id");
                    DBService.getInstance(context).updateCurrentIdByGroupId(groupId,String.valueOf(currentId));
                    LogHelper.d(TAG,"上传 UploadTask with server returned currentId = "+currentId+"groupId="+groupId);
                    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,photoItems);
            }else{
                LogHelper.d(TAG, "上传 UploadTask  photo path:"+photoPath+ "  fail ");
                listener.onPhotoUploadFail(photoPath,groupId);
            }
        }
    }

    public interface OnPhotoUploadListener {
        void onPhotoUploadSucceed(String photoPath, ArrayList<GroupPhotoItem> photoItems);
        void onPhotoUploadFail(String photoPath,String groupId);
    }
}
