package cn.axzo.msg.center.message.service.group;

import cn.axzo.maokai.api.vo.response.tree.ValueNode;
import cn.axzo.msg.center.domain.entity.MessageTemplateGroup;
import lombok.Getter;

import java.util.Collections;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author yanglin
 */
@Getter
public class GroupTemplates {

    private final RootNodeWrapper root;
    private final List<MessageTemplateGroup> templateGroups;

    public GroupTemplates(RootNodeWrapper root) {
        this(root, Collections.emptyList());
    }

    public GroupTemplates(RootNodeWrapper root, List<MessageTemplateGroup> templateGroups) {
        this.root = root;
        this.templateGroups = templateGroups;
    }

    public List<String> getTemplateCodes() {
        return templateGroups.stream()
                .map(MessageTemplateGroup::getTemplateCode)
                .distinct()
                .collect(toList());
    }

    public boolean groupContainsTemplate(String groupNodeCode, String templateCode) {
        ValueNode<NodeWrapper> node = root.findValueNode(groupNodeCode).orElse(null);
        if (node == null) return false;
        String groupPath = root.getPath(node);
        for (MessageTemplateGroup templateGroup : templateGroups) {
            if (!templateGroup.getTemplateCode().equals(templateCode))
                continue;
            if (templateGroup.getPath().startsWith(groupPath))
                return true;
        }
        return false;
    }

}