package com.efounder.chat.utils;

import android.content.Context;

import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.NotifyChatUIRefreshEvent;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.MessageEvent;
import com.efounder.chat.struct.StructFactory;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.manager.JFMessageManager;

import org.greenrobot.eventbus.EventBus;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * Created by YQS on 2017/11/7.
 */

public class ClearUserUtil {

    /**
     * 从数据库清空好友信息，清空角标
     *
     * @param context
     */
    public static void deleteUserFromDb(Context context, int userId, byte chatType) {
        WeChatDBManager.getInstance().deleteFriend(userId);
        //清除当前聊天的角标
        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(userId, chatType);

        JFMessageManager.getInstance().unreadZero(userId, chatType);
        int unReadCount = JFMessageManager.getInstance().
                getUnReadCount(userId, chatType);

        if (unReadCount == 0) {
            unReadCount = -1;
        }
        if (chatListItem != null) {
            chatListItem.setBadgernum(unReadCount);
            WeChatDBManager.getInstance().deleteChatListiItem(chatListItem);
            EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.DELETE));
        }

    }


    /**
     * 解散群
     *
     * @param context
     */
    public static void dissolveGroup(Context context, int groupId) {
        WeChatDBManager.getInstance().quitGroup(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)),
                groupId);

        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(groupId, StructFactory.TO_USER_TYPE_GROUP);

        JFMessageManager.getInstance().unreadZero(groupId, StructFactory.TO_USER_TYPE_GROUP);
        int unReadCount = JFMessageManager.getInstance().getUnReadCount(groupId, StructFactory.TO_USER_TYPE_GROUP);
        if (unReadCount == 0) {
            unReadCount = -1;
        }
        if (chatListItem != null) {
            chatListItem.setBadgernum(unReadCount);
            WeChatDBManager.getInstance().deleteChatListiItem(chatListItem);
            EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.DELETE));
        }
        //如果当前在对话界面 通知聊天界面退出
        EventBus.getDefault().post(new NotifyChatUIRefreshEvent(NotifyChatUIRefreshEvent.TYPE_EXIT,
                (byte)chatListItem.getChatType(),chatListItem.getUserId()));
    }
}
