package ai.pai.client.services;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;

import com.android.common.executors.ThreadExecutor;
import ai.pai.client.utils.HttpPostTask;
import com.android.common.utils.JSONParseUtils;
import com.android.common.utils.LogHelper;

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

import java.util.ArrayList;
import java.util.HashMap;

import ai.pai.client.beans.GroupInfo;
import ai.pai.client.beans.GroupMemberInfo;
import ai.pai.client.beans.GroupPhotoItem;
import ai.pai.client.beans.UploadPhotoBean;
import ai.pai.client.db.DBService;
import ai.pai.client.db.Preferences;
import ai.pai.client.utils.UrlContainer;

public class GroupService extends Service implements UploadTask.OnPhotoUploadListener {

    public interface GroupCommand{
        int COMMAND_JOIN_GROUP = 1;
        int COMMAND_LOCK_GROUP = 2;
        int COMMAND_FETCH_PHOTOS = 3;
        int COMMAND_UPLOAD_PHOTO = 4;
        int COMMAND_FETCH_GROUP_INFO = 5;
        int COMMAND_UNLOCK_GROUP = 6;
        int COMMAND_UPDATE_GROUP_INFO = 7;
        int COMMAND_DELETE_GROUP_MEMBER = 8;
        int COMMAND_QUIT_GROUP = 9;
        int COMMAND_REFRESH_PHOTOS = 10;
        int COMMAND_JOIN_GUIDE_GROUP = 11;
    }

    private Context context;
    private HttpPostTask lockGroupTask;
    private HttpPostTask unlockGroupTask;
    private HttpPostTask joinGuideGroupTask;
    private HttpPostTask joinGroupTask;
    private HttpPostTask fetchPhotosTask;
    private HttpPostTask refreshPhotosTask;
    private HttpPostTask fetchGroupInfoTask;
    private HttpPostTask updateGroupInfoTask;
    private HttpPostTask deleteGroupMemberTask;
    private HttpPostTask quitGroupTask;

    private static final String NullMsg = "";
    private static final String TAG = "czy";

    public interface GroupServiceListener{
        void onCommandCommitFail(int command, String msg);
        void onCommandCommitSuccess(int command, Object response);
    }

    public class MyBinder extends Binder{
       public GroupService getService(){
            return GroupService.this;
        }
    }
    private GroupServiceListener listener;

    @Override
    public void onCreate() {
        super.onCreate();
        this.context = this;
        LogHelper.d(TAG,"group service oncreate");
    }

    @Override
    public IBinder onBind(Intent intent) {
        LogHelper.d(TAG,"group service onBind");
        return new MyBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent==null){
            return super.onStartCommand(intent,flags,startId);
        }
        Bundle bundle= intent.getExtras();
        if(bundle==null){
            return super.onStartCommand(intent, flags, startId);
        }
        int command = bundle.getInt("command",0);
        LogHelper.d(TAG,"group service onStartCommand command is "+command);
        switch (command){
            case GroupCommand.COMMAND_JOIN_GROUP:
                doJoinGroupTask(bundle);
                break;
            case GroupCommand.COMMAND_LOCK_GROUP:
                doLockGroupTask(bundle);
                break;
            case GroupCommand.COMMAND_FETCH_PHOTOS:
                doUpdateGroupPhotosTask(bundle);
                break;
            case GroupCommand.COMMAND_UPLOAD_PHOTO:
                doUploadGroupPhotoTask(bundle);
                break;
            case GroupCommand.COMMAND_FETCH_GROUP_INFO:
                doFetchGroupInfoTask(bundle);
                break;
            case GroupCommand.COMMAND_UNLOCK_GROUP:
                doUnLockGroupTask(bundle);
                break;
            case GroupCommand.COMMAND_DELETE_GROUP_MEMBER:
                doDeleteGroupMemberTask(bundle);
                break;
            case GroupCommand.COMMAND_UPDATE_GROUP_INFO:
                doUpdateGroupInfoTask(bundle);
                break;
            case GroupCommand.COMMAND_QUIT_GROUP:
                doQuitGroupTask(bundle);
                break;
            case GroupCommand.COMMAND_JOIN_GUIDE_GROUP:
                doJoinGuideGroupTask(bundle);
                break;
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void registerServiceListener(GroupServiceListener listener){
        this.listener = listener;
    }

    public void unregisterServiceListener(){
        this.listener = null;
    }

    private synchronized void doJoinGuideGroupTask(final Bundle bundle){
        if(joinGuideGroupTask!=null && joinGuideGroupTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        LogHelper.d(TAG,"group service doJoinGuideGroupTask  ");
        final HashMap<String,String> params = new HashMap<String,String>();
        params.put("admin_id",bundle.getString("admin_id"));
        params.put("name",bundle.getString("name"));
        params.put("phone",bundle.getString("phone"));
        params.put("relative_person",String.valueOf(1));
        params.put("remark","");
        params.put("user_id", Preferences.getInstance(this).getUserId());

        joinGuideGroupTask = new HttpPostTask(context,params) {

            GroupInfo groupInfo = null;
            ArrayList<GroupPhotoItem> photoList = null;
            String msg = "";
            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    LogHelper.d(TAG,"group service doJoinGuideGroupTask  parseResponse "+response);
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    msg = json.getString("message");
                    if(status==200 || status==402011){
                        JSONObject data = json.getJSONObject("data");
                        JSONObject group = data.getJSONObject("group");
                        groupInfo = new GroupInfo();
                        groupInfo.groupId = group.getString("group_id");
                        groupInfo.groupAvatarId = group.getInt("group_default_avatar");
                        groupInfo.groupLock = group.getBoolean("group_lock");
                        groupInfo.groupName = group.getString("group_name");
                        groupInfo.createTime = group.getString("created_at");
                        groupInfo.groupFrom = group.getInt("group_from");
                        if(data.has("photos")){
                            JSONArray sessionArray = data.getJSONArray("photos");
                            if(sessionArray!=null && sessionArray.length()>0) {
                                photoList = new ArrayList<>();
                                for(int k = 0; k<sessionArray.length();k++){
                                    JSONObject sessionObj = sessionArray.getJSONObject(k);
                                    String sessionId = sessionObj.getString("session_id");
                                    JSONArray photoArray = sessionObj.getJSONArray("photos");
                                    if(photoArray!=null && photoArray.length()>0){
                                        for(int m = 0; m<photoArray.length();m++){
                                            JSONObject photoObj = photoArray.getJSONObject(m);
                                            GroupPhotoItem groupPhotoItem = GroupPhotoItem.parseFromJSON(photoObj);
                                            groupPhotoItem.sessionId = sessionId;
                                            photoList.add(groupPhotoItem);
                                        }
                                    }
                                }
                                LogHelper.d(TAG,"group service doJoinGuideGroupTask  get new photos ,count="+photoList.size());
                                DBService.getInstance(context).addGroupPhotoList(photoList);
                            }

                            int currentId = data.getInt("current_id");
                            DBService.getInstance(context).updateCurrentIdByGroupId(groupInfo.groupId,String.valueOf(currentId));
                        }
                        return  true;
                    }
                }catch (Exception e){
                    LogHelper.e(TAG,"group service doJoinGuideGroupTask error happen "+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                if(listener!=null){
                    listener.onCommandCommitFail(GroupCommand.COMMAND_JOIN_GUIDE_GROUP,msg);
                }
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                if(listener!=null){
                    listener.onCommandCommitSuccess(GroupCommand.COMMAND_JOIN_GUIDE_GROUP,groupInfo);
                }
            }
        };
        joinGuideGroupTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(),UrlContainer.GUIDE_GROUP_JOIN_URL);
    }

    private synchronized void doJoinGroupTask(final Bundle bundle){
        if(joinGroupTask!=null && joinGroupTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        LogHelper.d(TAG,"group service doJoinGroupTask  ");
        boolean isFromAPP = bundle.getBoolean("isFromAPP");
        final HashMap<String,String> params = new HashMap<String,String>();
        if(isFromAPP){
            params.put("group_id",bundle.getString("group_id"));
        }else{
            params.put("session_id",bundle.getString("group_id"));
        }
        params.put("nickname",bundle.getString("nickname"));
        params.put("user_id", Preferences.getInstance(this).getUserId());

        joinGroupTask = new HttpPostTask(context,params) {

            GroupInfo groupInfo = null;
            ArrayList<GroupPhotoItem> photoList = null;
            String msg = "";
            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    LogHelper.d(TAG,"group service doJoinGroupTask  parseResponse "+response);
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    msg = json.getString("message");
                    if(status==200 || status==402011){
                        JSONObject data = json.getJSONObject("data");
                        JSONObject group = data.getJSONObject("group");
                        groupInfo = new GroupInfo();
                        if(group.has("group_id")){
                            groupInfo.groupId = group.getString("group_id");
                        }else{
                            groupInfo.groupId = bundle.getString("group_id");
                        }
                        groupInfo.groupAvatarId = group.getInt("group_default_avatar");
                        groupInfo.groupLock = group.getBoolean("group_lock");
                        groupInfo.groupName = group.getString("group_name");
                        groupInfo.createTime = group.getString("created_at");
                        groupInfo.groupFrom = group.getInt("group_from");
//                        if(data.has("photos")){
//                            JSONArray sessionArray = data.getJSONArray("photos");
//                            if(sessionArray!=null && sessionArray.length()>0) {
//                                photoList = new ArrayList<>();
//                                for(int k = 0; k<sessionArray.length();k++){
//                                    JSONObject sessionObj = sessionArray.getJSONObject(k);
//                                    String sessionId = sessionObj.getString("session_id");
//                                    JSONArray photoArray = sessionObj.getJSONArray("photos");
//                                    if(photoArray!=null && photoArray.length()>0){
//                                        for(int m = 0; m<photoArray.length();m++){
//                                            JSONObject photoObj = photoArray.getJSONObject(m);
//                                            GroupPhotoItem groupPhotoItem = GroupPhotoItem.parseFromJSON(photoObj);
//                                            groupPhotoItem.sessionId = sessionId;
//                                            photoList.add(groupPhotoItem);
//                                        }
//                                    }
//                                }
//                                LogHelper.d(TAG,"group service doJoinGroupTask  get new photos ,count="+photoList.size());
//                                DBService.getInstance(context).addGroupPhotoList(photoList);
//                            }
//
//                            int currentId = data.getInt("current_id");
//                            DBService.getInstance(context).updateCurrentIdByGroupId(groupInfo.groupId,String.valueOf(currentId));
//                        }
                        return  true;
                    }
                }catch (Exception e){
                    LogHelper.e(TAG,"group service doJoinGroupTask error happen "+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                if(listener!=null){
                    listener.onCommandCommitFail(GroupCommand.COMMAND_JOIN_GROUP,msg);
                }
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                if(listener!=null){
                    listener.onCommandCommitSuccess(GroupCommand.COMMAND_JOIN_GROUP,groupInfo);
                }
            }
        };
        joinGroupTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(),
                isFromAPP ? UrlContainer.APP_GROUP_JOIN_URL:UrlContainer.SESSION_GROUP_JOIN_URL);
    }

    private synchronized void doUpdateGroupPhotosTask(final Bundle bundle){
        doRefreshGroupPhotoTask(bundle);
        if(fetchPhotosTask!=null && fetchPhotosTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        LogHelper.d(TAG,"group service doUpdateGroupPhotosTask  ");
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("group_id",bundle.getString("group_id"));
        params.put("user_id",Preferences.getInstance(this).getUserId());
        params.put("current_id",bundle.getString("current_id"));
        LogHelper.d(TAG,"doUpdateGroupPhotosTask with local currentId = "+bundle.getString("current_id"));

        fetchPhotosTask = new HttpPostTask(context,params) {
            ArrayList<GroupPhotoItem>  photoItems;
            String  groupId = bundle.getString("group_id");
            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){
                        LogHelper.d(TAG,"group service doUpdateGroupPhotosTask  parseResponse status 200");
                        JSONObject info = json.getJSONObject("data");
                        JSONArray sessionArray = info.getJSONArray("photos");
                        if(sessionArray!=null && sessionArray.length()>0) {
                            photoItems = new ArrayList<>();
                            for(int k = 0; k<sessionArray.length();k++){
                                JSONObject sessionObj = sessionArray.getJSONObject(k);
                                String sessionId = sessionObj.getString("session_id");
                                JSONArray photoArray = sessionObj.getJSONArray("photos");
                                if(photoArray!=null && photoArray.length()>0){
                                    for(int m = 0; m<photoArray.length();m++){
                                        JSONObject photoObj = photoArray.getJSONObject(m);
                                        GroupPhotoItem groupPhotoItem = GroupPhotoItem.parseFromJSON(photoObj);
                                        groupPhotoItem.sessionId = sessionId;
                                        photoItems.add(groupPhotoItem);
                                    }
                                }
                            }
                            LogHelper.d(TAG,"group service doUpdateGroupPhotosTask  get new photos ,count="+photoItems.size());
                            DBService.getInstance(context).addGroupPhotoList(photoItems);
                        }

                       int currentId = info.getInt("current_id");
                        DBService.getInstance(context).updateCurrentIdByGroupId(groupId,String.valueOf(currentId));
                        LogHelper.d(TAG,"doUpdateGroupPhotosTask with server currentId = "+currentId+"groupId="+groupId);
                        return true;
                    }
                }catch (Exception e){
                    LogHelper.e(TAG,"group service doUpdateGroupPhotosTask error happen "+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                if(listener!=null){
                    listener.onCommandCommitFail(GroupCommand.COMMAND_FETCH_PHOTOS,NullMsg);
                }
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                if(listener!=null){
                    listener.onCommandCommitSuccess(GroupCommand.COMMAND_FETCH_PHOTOS,photoItems);
                }
            }
        };
        fetchPhotosTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.GROUP_PHOTO_LIST_URL);
    }

    private synchronized void doRefreshGroupPhotoTask(final Bundle bundle){
        if(refreshPhotosTask!=null && refreshPhotosTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        LogHelper.d(TAG,"group service refreshPhotosTask  ");
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("group_id",bundle.getString("group_id"));
        params.put("user_id",Preferences.getInstance(this).getUserId());

        refreshPhotosTask = new HttpPostTask(context,params) {
            ArrayList<GroupPhotoItem>  photoItems;
            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){
                        LogHelper.d(TAG,"group service doRefreshGroupPhotoTask  parseResponse status 200");
                        JSONObject info = json.getJSONObject("data");
                        JSONArray photoArray = info.getJSONArray("photo_datas");
                        if(photoArray!=null && photoArray.length()>0){
                            photoItems = new ArrayList<GroupPhotoItem>();
                            for(int k = 0; k<photoArray.length();k++){
                                JSONObject photoObj = photoArray.getJSONObject(k);
                                GroupPhotoItem photoItem = new GroupPhotoItem();
                                photoItem.photoId = JSONParseUtils.getJSONString(photoObj.getString("photo_id"));
                                photoItem.commentNum = photoObj.getInt("comment_num");
                                photoItem.thumbupNum = photoObj.getInt("thumbup_num");
                                photoItems.add(photoItem);
                            }
                        }
                        return true;
                    }
                }catch (Exception e){
                    LogHelper.e(TAG,"group service doRefreshGroupPhotoTask error happen "+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                if(listener!=null){
                    listener.onCommandCommitFail(GroupCommand.COMMAND_REFRESH_PHOTOS,NullMsg);
                }
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                if(listener!=null && photoItems!=null){
                    LogHelper.d(TAG,"group service doRefreshGroupPhotoTask  total size = "+photoItems.size());
                    listener.onCommandCommitSuccess(GroupCommand.COMMAND_REFRESH_PHOTOS,photoItems);
                }
            }
        };
        refreshPhotosTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.GROUP_REFRESH_URL);
    }

    private void doUploadGroupPhotoTask(Bundle bundle) {
        String photoPath = bundle.getString("path");
        if(photoPath==null){
            return;
        }
        LogHelper.d(TAG,"group service doUploadGroupPhotoTask photo local path is  "+photoPath);
        UploadTask uploadTask = new UploadTask(this,bundle.getString("group_id"),this);
        uploadTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(),photoPath);
    }

    @Override
    public void onPhotoUploadSucceed(String photoPath, ArrayList<GroupPhotoItem> photoItems) {
        if(listener!=null){
            LogHelper.d(TAG,"group service onPhotoUploadSucceed ,new photos added ,size is "+photoItems.size());
            listener.onCommandCommitSuccess(GroupCommand.COMMAND_UPLOAD_PHOTO,photoItems);
        }
        DBService.getInstance(this).deleteUploadPhoto(photoPath);
        checkUploadTask();
    }

    @Override
    public void onPhotoUploadFail(String photoPath,String groupId) {
        UploadPhotoBean bean = new UploadPhotoBean();
        bean.photoPath = photoPath;
        bean.createTime = System.currentTimeMillis();
        bean.userId = Preferences.getInstance(this).getUserId();
        bean.groupId = groupId;
        bean.nickName = Preferences.getInstance(this).getNickName();
        DBService.getInstance(this).addUploadPhoto(bean);
        checkUploadTask();
    }

    private void checkUploadTask(){
        UploadPhotoBean bean = DBService.getInstance(this).getNextUploadPhotoBean();
        if(bean != null){
            LogHelper.d(TAG,"group service checkUploadTask and found another"+bean.photoPath);
            Bundle bundle = new Bundle();
            bundle.putString("group_id",bean.groupId);
            bundle.putString("path",bean.photoPath);
            doUploadGroupPhotoTask(bundle);
        }
    }

    private synchronized void doLockGroupTask(Bundle bundle){
        if(lockGroupTask!=null && lockGroupTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        LogHelper.d(TAG,"group service doLockGroupTask  ");
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("group_id",bundle.getString("group_id"));
        params.put("user_id",Preferences.getInstance(this).getUserId());

        lockGroupTask = new HttpPostTask(context,params) {
            String groupId;

            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    LogHelper.d(TAG,"group service doLockGroupTask  parseResponse "+response);
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){

                        return true;
                    }
                }catch (Exception e){
                    LogHelper.e(TAG,"group service doLockGroupTask error happen "+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                if(listener!=null){
                    listener.onCommandCommitFail(GroupCommand.COMMAND_LOCK_GROUP,NullMsg);
                }
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                if(listener!=null){
                    listener.onCommandCommitSuccess(GroupCommand.COMMAND_LOCK_GROUP,groupId);
                }
            }
        };
        lockGroupTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.GROUP_LOCK_URL);
    }

    private synchronized void doUpdateGroupInfoTask(Bundle bundle){
        if(updateGroupInfoTask!=null && updateGroupInfoTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        LogHelper.d(TAG,"group service doUpdateGroupInfoTask  ");
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("group_id",bundle.getString("group_id"));
        params.put("admin_id",bundle.getString("admin_id"));
        params.put("group_name",bundle.getString("group_name"));
        params.put("group_desc",bundle.getString("group_desc"));

        updateGroupInfoTask = new HttpPostTask(context,params) {
            String groupId;

            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    LogHelper.d(TAG,"group service doUpdateGroupInfoTask  parseResponse "+response);
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){

                        return true;
                    }
                }catch (Exception e){
                    LogHelper.e(TAG,"group service doUpdateGroupInfoTask error happen "+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                if(listener!=null){
                    listener.onCommandCommitFail(GroupCommand.COMMAND_UPDATE_GROUP_INFO,NullMsg);
                }
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                if(listener!=null){
                    listener.onCommandCommitSuccess(GroupCommand.COMMAND_UPDATE_GROUP_INFO,groupId);
                }
            }
        };
        updateGroupInfoTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.GROUP_UPDATE_URL);
    }

    private synchronized void doDeleteGroupMemberTask(Bundle bundle){
        if(deleteGroupMemberTask!=null && deleteGroupMemberTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        LogHelper.d(TAG,"group service deleteGroupMemberTask  ");
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("group_id",bundle.getString("group_id"));
        params.put("admin_id",bundle.getString("admin_id"));
        params.put("user_id",bundle.getString("user_id"));

        deleteGroupMemberTask = new HttpPostTask(context,params) {
            String groupId;

            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    LogHelper.d(TAG,"group service deleteGroupMemberTask  parseResponse "+response);
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){

                        return true;
                    }
                }catch (Exception e){
                    LogHelper.e(TAG,"group service deleteGroupMemberTask error happen "+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                if(listener!=null){
                    listener.onCommandCommitFail(GroupCommand.COMMAND_DELETE_GROUP_MEMBER,NullMsg);
                }
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                if(listener!=null){
                    listener.onCommandCommitSuccess(GroupCommand.COMMAND_DELETE_GROUP_MEMBER,groupId);
                }
            }
        };
        deleteGroupMemberTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.GROUP_REMOVE_MEMBER_URL);
    }

    private synchronized void doUnLockGroupTask(Bundle bundle){
        if(unlockGroupTask!=null && unlockGroupTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        LogHelper.d(TAG,"group service doUnLockGroupTask  ");
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("group_id",bundle.getString("group_id"));
        params.put("user_id",Preferences.getInstance(this).getUserId());

        unlockGroupTask = new HttpPostTask(context,params) {
            String groupId;

            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    LogHelper.d(TAG,"group service doUnLockGroupTask  parseResponse "+response);
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){

                        return true;
                    }
                }catch (Exception e){
                    LogHelper.e(TAG,"group service doUnLockGroupTask error happen "+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                if(listener!=null){
                    listener.onCommandCommitFail(GroupCommand.COMMAND_UNLOCK_GROUP,NullMsg);
                }
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                if(listener!=null){
                    listener.onCommandCommitSuccess(GroupCommand.COMMAND_UNLOCK_GROUP,groupId);
                }
            }
        };
        unlockGroupTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.GROUP_UNLOCK_URL);
    }

    private void doFetchGroupInfoTask(Bundle bundle){
        if(fetchGroupInfoTask!=null && fetchGroupInfoTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        LogHelper.d(TAG,"group service doFetchGroupInfoTask  ");
        HashMap<String,String> params = new HashMap<String,String>();
        String groupId =bundle.getString("group_id");
        if(groupId.length()==0){
            return;
        }
        final String userId = Preferences.getInstance(this).getUserId();
        if(userId.length()==0){
            return;
        }
        params.put("group_id",groupId);
        params.put("user_id",userId);


        fetchGroupInfoTask = new HttpPostTask(this,params) {
            boolean isLocked;
            String groupName;
            boolean isAdmin;
            ArrayList<GroupMemberInfo> memberList;

            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){
                        LogHelper.d(TAG,"group service doFetchGroupInfoTask  parseResponse status 200");
                        JSONObject info = json.getJSONObject("data");
                        JSONObject groupObj = info.getJSONObject("group");
                        isLocked = groupObj.getBoolean("group_lock");
                        String adminId = groupObj.getString("admin_id");
                        isAdmin = adminId.equals(userId);
                        groupName = JSONParseUtils.getJSONString(groupObj.getString("group_name"));
                        memberList = new ArrayList<GroupMemberInfo>();
                        JSONObject usersObj = info.getJSONObject("users");
                        JSONArray memberArray = usersObj.getJSONArray("passed");
                        if(memberArray!= null && memberArray.length()>0){
                            for(int k =0; k<memberArray.length();k++){
                                JSONObject memberObj = memberArray.getJSONObject(k);
                                GroupMemberInfo memberInfo = new GroupMemberInfo();
                                memberInfo.isAdmin = memberObj.getBoolean("admin");
                                memberInfo.nickName=JSONParseUtils.getJSONString(memberObj.getString("nickname"));
                                memberInfo.userId = JSONParseUtils.getJSONString(memberObj.getString("user_id"));
                                memberInfo.avatarUrl= JSONParseUtils.getJSONString(memberObj.getString("avatar"));
                                if(memberInfo.isAdmin || memberInfo.userId.equals(adminId)){
                                    memberInfo.isAdmin = true;
                                }
                                memberList.add(memberInfo);
                            }
                        }
                        return true;
                    }
                }catch (Exception e){
                    LogHelper.e(TAG,"group service doFetchGroupInfoTask error happen "+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                if(listener!=null){
                    listener.onCommandCommitFail(GroupCommand.COMMAND_FETCH_GROUP_INFO,NullMsg);
                }
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                Bundle bundle = new Bundle();
                bundle.putString("groupName",groupName);
                bundle.putBoolean("isLocked",isLocked);
                bundle.putBoolean("isAdmin",isAdmin);
                bundle.putSerializable("memberList",memberList);
                if(listener!=null){
                    listener.onCommandCommitSuccess(GroupCommand.COMMAND_FETCH_GROUP_INFO,bundle);
                }
            }
        };
        fetchGroupInfoTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.GROUP_DETAIL_URL);
    }

    private synchronized void doQuitGroupTask(Bundle bundle){
        if(quitGroupTask!=null && quitGroupTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        LogHelper.d(TAG,"group service quitGroupTask  ");
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("group_id",bundle.getString("group_id"));
        params.put("user_id",Preferences.getInstance(this).getUserId());

        quitGroupTask = new HttpPostTask(context,params) {

            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    LogHelper.d(TAG,"group service quitGroupTask  parseResponse "+response);
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){
                        return true;
                    }
                }catch (Exception e){
                    LogHelper.e(TAG,"group service quitGroupTask error happen "+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                if(listener!=null){
                    listener.onCommandCommitFail(GroupCommand.COMMAND_QUIT_GROUP,NullMsg);
                }
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                if(listener!=null){
                    listener.onCommandCommitSuccess(GroupCommand.COMMAND_QUIT_GROUP,NullMsg);
                }
            }
        };
        quitGroupTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.GROUP_QUIT_URL);
    }
}
