package com.efounder.chat.utils;

import com.efounder.chat.event.SystemInitOverEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.struct.IMStruct002;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import static com.efounder.chat.struct.MessageChildTypeConstant.subtype_format_text;
import static com.efounder.chat.struct.MessageChildTypeConstant.subtype_mZoneNotification;

/**
 * 处理接收到的普通消息
 * @author will
 */
public class HandleReceiveCommonMessageUtil {

    public static void handleMessage(IMStruct002 imStruct002) {
        //处理空间推送消息
        if (imStruct002.getMessageChildType() == subtype_mZoneNotification) {
            handleZoneMessage(imStruct002);
        } else if (imStruct002.getMessageChildType() == subtype_format_text) {
            //处理@消息
            //handleFormatMessage(imStruct002);
        }

    }

    /**
     * 处理空间推送消息
     */
    private static void handleZoneMessage(IMStruct002 imStruct002) {
        try {
            JSONObject jsonObject = new JSONObject(new String(imStruct002.getBody()));
            String pushType = jsonObject.optString("pushType");
            if (pushType.equals("newShortPost")) {
                //新动态
                EnvironmentVariable.setProperty("zone_has_new_post", "true");
            } else {
                //新消息，累加
                int count;
                String messageCount = EnvironmentVariable.getProperty("zone_has_new_message");
                if (messageCount != null) {
                    try {
                        count = Integer.valueOf(messageCount);
                    } catch (Exception e) {
                        e.printStackTrace();
                        count = 0;
                    }
                } else {
                    count = 0;
                }
                count++;
                EnvironmentVariable.setProperty("zone_has_new_message", count + "");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        EventBus.getDefault().post(new SystemInitOverEvent());

    }

    /**
     * 处理@消息，将未读的@存到EV中，在列表中显示
     * @param imStruct002
     */
    private static void handleFormatMessage(IMStruct002 imStruct002) {
        try {
            if (TextFormatMessageUtil.checkHasAtMe(imStruct002)) {
                TextFormatMessageUtil.saveMentionHintEV(imStruct002);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
