package com.izouma.nineth.dto;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.izouma.nineth.domain.Tag;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(value = {"hibernateLazyInitializer"}, ignoreUnknown = true)
public class MintActivityRule {

    private MintActivityRuleDetail detail;

    private List<MintActivityRule> and;

    private List<MintActivityRule> or;

    public Set<Tag> getTags() {
        return getTags(this);
    }

    public static Set<Tag> getTags(MintActivityRule rule) {
        if (rule == null) return Collections.emptySet();
        Set<Tag> tags = new HashSet<>();
        if (rule.getDetail() != null) {
            tags.add(rule.getDetail().getTag());
        }
        if (CollectionUtils.isNotEmpty(rule.getAnd())) {
            tags.addAll(rule.getAnd().stream().flatMap(child -> getTags(child).stream()).collect(Collectors.toList()));
        }
        if (CollectionUtils.isNotEmpty(rule.getOr())) {
            tags.addAll(rule.getOr().stream().flatMap(child -> getTags(child).stream()).collect(Collectors.toList()));
        }
        return tags;
    }
}
