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

import cn.axzo.msg.center.domain.entity.MessageGroupNode;
import cn.axzo.msg.center.domain.entity.MessageTemplateGroup;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

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

/**
 * @author yanglin
 */
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
public class TemplateGroups {

    private final List<MessageTemplateGroup> groups;
    private final List<MessageGroupNode> nodes;

    TemplateGroups() {
        this(Collections.emptyList(), Collections.emptyList());
    }

    public List<MessageGroupNode> collectPathNodes(String templateCode) {
        List<String> collectedNodeCodes = groups.stream()
                .filter(group -> group.getTemplateCode().equals(templateCode))
                .map(MessageTemplateGroup::getPathSegments)
                .flatMap(Collection::stream)
                .distinct()
                .collect(toList());
        return collectedNodeCodes.stream()
                .map(this::findNode)
                .map(node -> node.orElse(null))
                .filter(Objects::nonNull)
                .collect(toList());
    }

    private Optional<MessageGroupNode> findNode(String nodeCode) {
        return nodes.stream()
                .filter(node -> node.getCode().equals(nodeCode))
                .findFirst();
    }

}