package com.elab.spring.intercept;

import com.elab.mq.model.MessageModel;
import com.elab.redis.annotation.EnableElabRedis;
import com.elab.spring.config.RmqConfiguration;
import org.json.JSONException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.redisson.spring.starter.RedissonAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @Module TODO
 * @Description TODO
 * @Author liukaixiong
 * @Date 2020/12/31 14:28
 */
@RunWith(SpringRunner.class)
@EnableConfigurationProperties(value = {RedisProperties.class})
@SpringBootTest(classes = {RmqConfiguration.class, RedissonAutoConfiguration.class})
@EnableElabRedis
public class RMQCacheConsumerInterceptorTest {

    @Autowired
    private RMQCacheConsumerInterceptor rmqCacheConsumerInterceptor;

    @Autowired
    private RMQCacheProducerInterceptor producerInterceptor;

    @Test
    public void check() {

    }

    public MessageModel sendMsg() {
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        jsonObject.put("key", "test");
        MessageModel messageModel = new MessageModel("A", "B", "C", jsonObject.toString());
        messageModel.setInvokeTime(1000L);
        producerInterceptor.check(messageModel,"");
        return messageModel;
    }

    @Test
    public void success() throws JSONException {
        successProcess();
    }

    private void successProcess() {
        MessageModel messageModel = sendMsg();
        messageModel.setInvokeTime(1000L);
        boolean check = rmqCacheConsumerInterceptor.check(messageModel,"");
        if (check) {
            rmqCacheConsumerInterceptor.success(messageModel,"");
        }
    }

    @Test
    public void error() {
        errorProcess(null);
    }

    /**
     * 异常场景触发
     * @param fixedProducerId   固定的producer编号
     */
    private void errorProcess(Integer fixedProducerId) {
        MessageModel messageModel = sendMsg();
        messageModel.setInvokeTime(1000L);
        if (fixedProducerId != null) {
            messageModel.setProducerId(fixedProducerId + "");
        }
        boolean check = rmqCacheConsumerInterceptor.check(messageModel,"");
        if (check) {
            rmqCacheConsumerInterceptor.error(messageModel, "",null);
        }
    }

    @Test
    public void retryTest() {
        boolean isSuccess = false;
        int retryCount = 2;
        for (int i = 0; i < retryCount; i++) {
            if (isSuccess) {
                successProcess();
            } else {
                errorProcess(100);
            }
        }
    }
}