package org.jim.server.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jim.common.ImPacket;
import org.jim.common.ImStatus;
import org.jim.common.http.HttpConst;
import org.jim.common.packets.Command;
import org.jim.common.packets.EvaluationReqBody;
import org.jim.common.packets.InputIndicatorReqBody;
import org.jim.common.packets.RespBody;
import org.jim.common.utils.ImKit;
import org.jim.common.utils.JsonKit;
import org.tio.core.ChannelContext;

import java.io.UnsupportedEncodingException;

/**
 * @author Darren
 * @date 2020/2/13 19:24
 */
public class EvaluationKit {

    private static Logger log = Logger.getLogger(EvaluationKit.class);

    /**
     * 转换为消息结构;
     * @param body
     * @return
     */
    public static EvaluationReqBody toReqBody(byte[] body){
        EvaluationReqBody inputIndicatorReqBody = parseReqBody(body);
        if( null != inputIndicatorReqBody ){
            if(validateReqBody(inputIndicatorReqBody) ){
                return inputIndicatorReqBody;
            }
        }
        return null;
    }

    /**
     * 验证消息体中的值
     * @param reqBody
     * @return
     */
    private static boolean validateReqBody(EvaluationReqBody reqBody) {
        boolean b1 = StringUtils.isNotEmpty(reqBody.getGroup_id());
        boolean b2 = StringUtils.isNotEmpty(reqBody.getFrom());
        boolean b3 = null != reqBody.getChatType();
        return (b1 && b2 && b3);
    }

    /**
     * 转换为消息结构;
     * @param body
     * @return
     */
    private static EvaluationReqBody parseReqBody(byte[] body) {
        if(body == null) {
            return null;
        }
        EvaluationReqBody reqBody = null;
        try {
            String text = new String(body, HttpConst.CHARSET_NAME);
            reqBody = JsonKit.toBean(text, EvaluationReqBody.class);
            if( null != reqBody){
                return reqBody;
            }
        } catch (UnsupportedEncodingException e) {
            log.error(e.toString());
        }
        return reqBody;
    }

    /**
     * 数据格式不正确响应包
     * @param channelContext
     * @return imPacket
     * @throws Exception
     */
    public static ImPacket dataInCorrectRespPacket(ChannelContext channelContext) {
        RespBody respBody = new RespBody(Command.COMMAND_EVALUATION_REQ, ImStatus.C10026);
        ImPacket respPacket = ImKit.ConvertRespPacket(respBody, channelContext);
        respPacket.setStatus(ImStatus.C10026);
        return respPacket;
    }

    /**
     * 成功响应包
     * @param channelContext
     * @return
     * @throws Exception
     */
    public static ImPacket sendSuccessRespPacket(ChannelContext channelContext) {
        RespBody respBody = new RespBody(Command.COMMAND_EVALUATION_RESP,ImStatus.C10000);
        ImPacket respPacket = ImKit.ConvertRespPacket(respBody, channelContext);
        respPacket.setStatus(ImStatus.C10000);
        return respPacket;
    }

}
