package org.ssssssss.magicapi.rocketmq.service;


import org.apache.commons.lang3.StringUtils;
import org.ssssssss.magicapi.core.model.MagicEntity;
import org.ssssssss.magicapi.core.service.AbstractPathMagicResourceStorage;
import org.ssssssss.magicapi.rocketmq.model.RocketMqInfo;

import java.util.List;

/**
 * @author zzy
 */
public class RocketMqInfoMagicResourceStorage extends AbstractPathMagicResourceStorage<RocketMqInfo> {

    @Override
    public String folder() {
        return "rocketmq";
    }

    @Override
    public Class<RocketMqInfo> magicClass() {
        return RocketMqInfo.class;
    }

    @Override
    public void validate(RocketMqInfo entity) {
        notBlank(entity.getTopic(), TOPIC_ID_REQUIRED);
        String currentTag = StringUtils.isEmpty(entity.getTag()) ? "*" : entity.getTag();
        List<MagicEntity> files = magicResourceService.files(folder());
        boolean exists = files.stream().filter(x -> !x.getId().equals(entity.getId())).anyMatch(x -> {
            String topic = ((RocketMqInfo) x).getTopic();
            String tag = ((RocketMqInfo) x).getTag();
            if (StringUtils.isEmpty(tag)) {
                tag = "*";
            }
            return topic.equals(entity.getTopic()) && tag.equals(currentTag);
        });
        isTrue(!exists, TOPIC_TAG_REPEAT);
    }

    @Override
    public String buildMappingKey(RocketMqInfo info) {
        return buildMappingKey(info, magicResourceService.getGroupPath(info.getGroupId()));
    }
}
