package cn.axzo.workflow.starter.handler.execute.interceptor;

import cn.axzo.framework.rocketmq.EventConsumer;
import cn.axzo.workflow.starter.common.exception.WorkflowEngineStarterException;
import cn.axzo.workflow.starter.common.exception.WorkflowListenerExecutionException;
import cn.axzo.workflow.starter.handler.execute.ListenerExecutor;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;

import java.util.function.Consumer;

public final class LogInterceptor extends AbstractListenerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(LogInterceptor.class);

    @Override
    public <T> void execute(ListenerExecutor executor, Consumer<T> consumer, EventConsumer.Context context, T t) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        if (log.isDebugEnabled()) {
            log.debug("--- starting handle mq ---- ");
        }
        if (log.isDebugEnabled()) {
            log.debug("messageId: {}, eventCode: {}, messageBody: {}", context.getMsgId(), context.getEventCode().toString(), JSON.toJSONString(t));
        }
        try {
            getNext().execute(executor, consumer, context, t);
        } catch (WorkflowListenerExecutionException e) {
            // fail_fast mode , will be ignored
        } catch (Throwable e) {
            if (e instanceof WorkflowEngineStarterException) {
                // 如果业务想使用异常来正确结束事件处理，可以抛出该移除类型
            } else {
                throw e;
            }
        } finally {
            stopWatch.stop();
            if (log.isDebugEnabled()) {
                log.debug("--- messageId: {} finished ,timeCost:{} ms ---", executor.getClass().getSimpleName(), stopWatch.getTotalTimeMillis());
            }
        }
    }
}
