package cn.axzo.msg.center.notices.manager;

import cn.axzo.msg.center.notices.common.constans.CommonConstants;
import cn.axzo.msg.center.notices.common.domain.MessageContext;
import cn.axzo.msg.center.notices.manager.api.RetryStrategy;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 重试策略实现类
 *
 * @author zhaoyong_sh
 * @see RetryStrategyImpl
 * @since 2021-05-19 10:42
 */
@Slf4j
@Service("retryStrategy")
public class RetryStrategyImpl implements RetryStrategy {

    @Value("${notice.retry.rule}")
    private String noticeRetryRule;

    @Override
    public List<Integer> getRetryStrategy() {
        List<Integer> retryStrategyList = parseRetryStrategy(noticeRetryRule);
        if(retryStrategyList.size() > CommonConstants.MAX_RETRY_COUNT) {
            return retryStrategyList.subList(0, CommonConstants.MAX_RETRY_COUNT);
        }
        return retryStrategyList;
    }

    @Override
    public Integer getNextNotifySecond(MessageContext context) {
        if(context == null) {
            return null;
        }
        if(context.getRetryCount() == null) {
            return null;
        }
        if(StringUtils.isEmpty(context.getNotifyRule())) {
            return null;
        }
        String notifyRule = context.getNotifyRule();
        final List<Integer> notifyRules = Lists.newArrayList();
        Splitter.on(CommonConstants.COMMA_SYMBOL).split(notifyRule).forEach(e -> notifyRules.add(Integer.parseInt(e)));
        log.info("notify message get notify rule {}", notifyRules.toString());
        if(context.getRetryCount() >= notifyRules.size()) {
            return null;
        }
        return notifyRules.get(context.getRetryCount());
    }

    /**
     * 解析重试策略
     * @param notifyRule
     * @return
     */
    private List<Integer> parseRetryStrategy(String notifyRule) {
        List<Integer> delaySeconds = Lists.newArrayList();
        for(String strategy : notifyRule.split(CommonConstants.COMMA_SYMBOL)){
            try {
                int delaySecond = Integer.parseInt(strategy);
                delaySeconds.add(delaySecond);
            } catch (Exception e) {
                delaySeconds.clear();
                break;
            }
        }
        if(CollectionUtils.isEmpty(delaySeconds)){
            return Lists.newArrayList(30, 60, 60);
        }
        return delaySeconds;
    }

}
