package ru.yandex.qe.dispenser.domain.base_resources;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public final class BaseResourceMdsRelation {

    private final List<BaseResourceMdsRelationTerm> terms;
    private final Set<ResourceAndSegmentsId> allResources;

    @JsonCreator
    public BaseResourceMdsRelation(@JsonProperty("terms") List<BaseResourceMdsRelationTerm> terms) {
        this.terms = terms;
        this.allResources = terms != null
                ? terms.stream().map(t -> new ResourceAndSegmentsId(t.getResourceId(), t.getSegmentIds()))
                .collect(Collectors.toSet())
                : Set.of();
    }

    public static Builder builder() {
        return new Builder();
    }

    public static Builder builder(BaseResourceMdsRelation value) {
        return new Builder(value);
    }

    public List<BaseResourceMdsRelationTerm> getTerms() {
        return terms;
    }

    @JsonIgnore
    public Set<ResourceAndSegmentsId> getAllResources() {
        return allResources;
    }

    @JsonIgnore
    public boolean isLocalEvaluation() {
        return false;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        BaseResourceMdsRelation that = (BaseResourceMdsRelation) o;
        return Objects.equals(terms, that.terms);
    }

    @Override
    public int hashCode() {
        return Objects.hash(terms);
    }

    @Override
    public String toString() {
        return "BaseResourceMdsRelation{" +
                "terms=" + terms +
                '}';
    }

    public static final class Builder {

        private final List<BaseResourceMdsRelationTerm> terms = new ArrayList<>();

        private Builder() {
        }

        private Builder(BaseResourceMdsRelation value) {
            this.terms.addAll(value.terms != null ? value.terms : List.of());
        }

        public Builder addTerm(BaseResourceMdsRelationTerm term) {
            this.terms.add(term);
            return this;
        }

        public Builder addTerms(Collection<? extends BaseResourceMdsRelationTerm> terms) {
            this.terms.addAll(terms);
            return this;
        }

        public Builder addTerms(BaseResourceMdsRelationTerm... terms) {
            this.terms.addAll(List.of(terms));
            return this;
        }

        public BaseResourceMdsRelation build() {
            return new BaseResourceMdsRelation(terms);
        }

    }

}
