package org.ssssssss.magicapi.rocketmq.service;

import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.transaction.annotation.Transactional;
import org.ssssssss.magicapi.utils.ScriptManager;
import org.ssssssss.script.MagicScriptContext;

/**
 * @author zzy
 */
public interface RocketMqService {

    /**
     * 消费默认实现
     *
     * @param scriptName
     * @param script
     * @param msg
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    default boolean consume(String scriptName, String script, MessageExt msg) {
        MagicScriptContext magicScriptContext = new MagicScriptContext();
        magicScriptContext.setScriptName(scriptName);
        magicScriptContext.set("msg", msg);
        beforeConsume(msg, magicScriptContext);
        Object result = ScriptManager.executeScript(script, magicScriptContext);
        if (result != null) {
            failConsume(msg, magicScriptContext);
            return false;
        }
        afterConsume(msg, magicScriptContext);
        return true;
    }

    /**
     * 发送消息前处理
     *
     * @param topic 主题
     * @param tag   标签
     * @param msg   消息
     * @return
     */
    boolean beforeProduce(String topic, String tag, Object msg);

    /**
     * 发送消息后处理
     *
     * @param topic 主题
     * @param tag   标签
     * @param msg   消息
     * @return
     */
    boolean afterProduce(String topic, String tag, Object msg);

    /**
     * 发送消息失败处理
     *
     * @param topic 主题
     * @param tag   标签
     * @param msg   消息
     * @return
     */
    boolean failProduce(String topic, String tag, Object msg);

    /**
     * 消费消息前处理
     *
     * @param messageExt         消息体
     * @param magicScriptContext magic 上下文
     * @return
     */
    boolean beforeConsume(MessageExt messageExt, MagicScriptContext magicScriptContext);

    /**
     * 消费消息后处理
     *
     * @param messageExt         消息体
     * @param magicScriptContext magic 上下文
     * @return
     */
    boolean afterConsume(MessageExt messageExt, MagicScriptContext magicScriptContext);

    /**
     * 消费消息失败处理
     *
     * @param messageExt         消息体
     * @param magicScriptContext magic 上下文
     * @return
     */
    boolean failConsume(MessageExt messageExt, MagicScriptContext magicScriptContext);
}
