package com.efounder.chat.manager;

import android.content.Context;
import android.view.View;
import android.widget.AdapterView;

import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.adapter.ChatMenuAdapter;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.AppConstant;
import com.efounder.chat.model.ChatMenuModel;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.widget.ExpandGridView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.service.Registry;
import com.efounder.utils.ResStringUtil;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import static com.efounder.chat.model.ChatMenuModel.COMMON;
import static com.efounder.chat.model.ChatMenuModel.FILE;
import static com.efounder.chat.model.ChatMenuModel.PICTURE;
import static com.efounder.chat.model.ChatMenuModel.TAKEPIC;
import static com.efounder.chat.model.ChatMenuModel.VEDIO;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.mobilecomps.contacts.User.GROUPCREATOR;
import static com.efounder.mobilecomps.contacts.User.GROUPMANAGER;

/**
 * 聊天菜单管理（图片 拍照 小视频 文件等）
 * Created by yqs on 2016/12/22.
 */

public class ChatMenuManager {
    private Context mContext;
    private OnMenuClickListener menuClickListener;
    private int pageMaxCount = 6;//一页最大显示6个菜单按钮
    private static final String GROUP_OWNER = "0";//群主
    private static final String GROUP_MANAGER = "1";//管理员
    private static final String GROUP_ALL = "2";//所有人
    private static final String GROUP_OM = "3";//群主或者管理员


    public ChatMenuManager(Context mContext) {
        this.mContext = mContext;
    }

    public List<View> getGridViews(int toUserId, int chatType,String chatPermission) {

        List<View> views = new ArrayList<>();
        List<StubObject> stubMenuList = null;
//        List<StubObject> stubObjectList = Registry.getRegEntryList("ChatMenuRoot");
//        if (stubObjectList != null) {
//            for (StubObject stubObject : stubObjectList) {
//                List<StubObject> subMenus = Registry.getRegEntryList((String) stubObject.getID());
//                List<StubObject> stubMenuList = Registry.getRegEntryList((String) stubObject.getStubTable().get("id"));
//            }
//        }
        if (chatType == StructFactory.TO_USER_TYPE_GROUP) {
            stubMenuList = Registry.getRegEntryList("chatGroup");
        } else {
            User user = WeChatDBManager.getInstance().getOneUserById(toUserId);
            if (user.getType() == User.PERSONALFRIEND) {
                stubMenuList = Registry.getRegEntryList("chatSingle");
            } else {
                stubMenuList = Registry.getRegEntryList("chatAppNumber");
            }
        }

        //TODO 不清楚为啥前四个不配置到xml文件中，导致后续都需要特殊处理。edit lch
        List<ChatMenuModel> menuReslist = new ArrayList<>();
        if(chatPermission.equals("")||chatPermission.equals("all")) {
            menuReslist.add(new ChatMenuModel(PICTURE, ResStringUtil.getString(R.string.attach_picture), R.drawable.icon_chat_pic));
            menuReslist.add(new ChatMenuModel(TAKEPIC, ResStringUtil.getString(R.string.attach_take_pic), R.drawable.icon_chat_photo));
            menuReslist.add(new ChatMenuModel(VEDIO, ResStringUtil.getString(R.string.wechatview_attach_video), R.drawable.icon_chat_vedio));
            menuReslist.add(new ChatMenuModel(FILE, ResStringUtil.getString(R.string.attach_file), R.drawable.icon_chat_file));
        }else{
            String[] chatPermissionArray = chatPermission.split(",");
            for (int i = 0; i <chatPermissionArray.length ; i++) {
                if(chatPermissionArray[i].equals("pic")){
                    menuReslist.add(new ChatMenuModel(PICTURE, ResStringUtil.getString(R.string.attach_picture), R.drawable.icon_chat_pic));
                }else if(chatPermissionArray[i].equals("camera")){
                    menuReslist.add(new ChatMenuModel(TAKEPIC, ResStringUtil.getString(R.string.attach_take_pic), R.drawable.icon_chat_photo));
                }else if(chatPermissionArray[i].equals("video")){
                    menuReslist.add(new ChatMenuModel(VEDIO, ResStringUtil.getString(R.string.wechatview_attach_video), R.drawable.icon_chat_vedio));
                }else if(chatPermissionArray[i].equals("file")){
                    menuReslist.add(new ChatMenuModel(FILE, ResStringUtil.getString(R.string.attach_file), R.drawable.icon_chat_file));
                }
            }
        }

        // menuReslist.add(new ChatMenuModel(WEBPAGE, "网址", R.drawable.icon_chat_vedio));
        //   menuReslist.add(new ChatMenuModel(COMMON, "通用", R.drawable.icon_chat_vedio));
        if (stubMenuList != null) {
            for (StubObject stubObject : stubMenuList) {
                Hashtable<String, String> hashtable = stubObject.getStubTable();
                boolean isHavePerMission = checkHavePermission(toUserId, chatType, hashtable,chatPermission);
                if (!isHavePerMission) {
                    //没有此菜单权限，继续循环
                    continue;
                }
                ChatMenuModel model = new ChatMenuModel();
                model.setType(COMMON);
                String filepath = AppConstant.APP_ROOT + "/res/unzip_res/menuImage/" + hashtable.get("icon");
                model.setLocalIcon(filepath);
                model.setName(hashtable.get("caption"));
                model.setStubObject(stubObject);


                menuReslist.add(model);
            }
        }


        views.addAll(getMenuGridChildView(menuReslist));

        return views;
    }


    //检查是否有此菜单的权限
    private boolean checkHavePermission(int toUserId, int chatType, Hashtable<String, String> hashtable,String chatPermission) {
        if (!hashtable.containsKey("permission")) {
            return true;//没有配置权限表示都有
        }

        String permissionId = hashtable.get("permission");
        if (permissionId == null || "".equals(permissionId)) {
            return true;
        }
//        if (chatType != StructFactory.TO_USER_TYPE_GROUP) {
//            return true;//目前不是群聊不控制权限，所以返回有权限
//        }
        if(chatType == StructFactory.TO_USER_TYPE_GROUP) {
            //自己的imid
            String myUserId = EnvironmentVariable.getProperty(CHAT_USER_ID);
            User tempUser = WeChatDBManager.getInstance().getGroupUserInfo(toUserId, Integer.valueOf(myUserId));
            if (tempUser == null) {
                //群组成员没有从服务器加载完，不显示显示权限，返回重新进加载完就可以了
                return false;
            }
            if (tempUser.getGroupUserType() == GROUPCREATOR && permissionId.equals(GROUP_OWNER)) {
                //群主才拥有次权限
                return true;
            } else if (tempUser.getGroupUserType() == GROUPMANAGER && permissionId.equals(GROUP_MANAGER)) {
                // //管理员才拥有次权限
                return true;
            } else if ((tempUser.getGroupUserType() == GROUPMANAGER
                    || tempUser.getGroupUserType() == GROUPCREATOR) && permissionId.equals(GROUP_OM)) {
                //管理员或者群主才有次权限
                return true;
            } else if (permissionId.equals(GROUP_ALL)) {
                //所有人都有
                return true;
            } else {
                return false;
            }
        }else if(chatType == StructFactory.TO_USER_TYPE_PERSONAL){
            if(chatPermission.equals("")||chatPermission.equals("all")) {
               return true;
            }else{
                String[] chatPermissionArray = chatPermission.split(",");
                for (int i = 0; i <chatPermissionArray.length ; i++) {
                    if(chatPermissionArray[i].equals(permissionId)){
                        return  true;
                    }
                }
            }
        }
        return  false;
    }


    /**
     * 获取菜单gridview
     *
     * @param
     * @return
     */
    private List<View> getMenuGridChildView(List<ChatMenuModel> list) {
        List<View> views = new ArrayList<>();
        int count = 0;
        int start = 0;
        int end = pageMaxCount;
        if (pageMaxCount > list.size()) {
            end = list.size();
        }
        //获取最大有几个gridview
        if (list.size() % pageMaxCount == 0) {
            count = list.size() / pageMaxCount;
        } else {
            count = list.size() / pageMaxCount + 1;
        }
        //gridview设置adapter
        for (int i = 0; i < count; i++) {
            View view = View.inflate(mContext, R.layout.bottom_menu_gridview,
                    null);
            ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
            final List<ChatMenuModel> myList = list.subList(start, end);
            start = end;
            end = end + pageMaxCount;
            if (end > list.size() - 1) {
                end = list.size();
            }

            final ChatMenuAdapter adapter = new ChatMenuAdapter(
                    mContext, myList, R.layout.gridview_menu_item);
            gv.setAdapter(adapter);
            //设置点击事件
            gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    ChatMenuModel model = myList.get(position);
                    if (menuClickListener != null) {
                        menuClickListener.onMenuItemClick(model);
                    }
                }
            });

            views.add(view);
        }

        return views;
    }


    public void setOnMenuClickListener(OnMenuClickListener listener) {
        this.menuClickListener = listener;
    }

    public interface OnMenuClickListener {
        public void onMenuItemClick(ChatMenuModel model);
    }
}
