package ru.yandex.canvas.repository.video;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

public abstract class QueryBuilderBase<T extends QueryBuilderBase<T>> {

    protected List<Criteria> criteries = new ArrayList<>();

    protected Criteria[] getCriteries() {
        return criteries.toArray(new Criteria[criteries.size()]);
    }

    protected List<Criteria> getCriteriesList() {
        return Collections.unmodifiableList(criteries);
    }

    public T or(QueryBuilderBase<T>... builders) {
        return or(Arrays.asList(builders));
    }

    public T or(List<QueryBuilderBase<T>> builders) {

        criteries.add(new Criteria()
                .orOperator(
                        builders.stream().map(e -> new Criteria().andOperator(e.getCriteries()))
                                .toArray(Criteria[]::new))

        );

        return (T) this;
    }

    public T and(QueryBuilderBase<?>... builders) {
        return and(Arrays.asList(builders));
    }

    public T and(List<QueryBuilderBase<?>> builders) {
        criteries.add(new Criteria()
                .andOperator(builders.stream().flatMap(e -> e.getCriteriesList().stream()).toArray(Criteria[]::new)));
        return (T) this;
    }

    public Query build() {
        Query query = new Query();

        for (Criteria criteria : criteries) {
            query.addCriteria(criteria);
        }

        return query;
    }

}
