﻿namespace NSolrClient.Selection.Filters.Internals
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using NSolrClient.Practices;
    using NSolrClient.ValueSerializers;

    public abstract class MultipleLogicalOperator : FilterBuilder, IBoostOperatorSupported
    {
        private readonly IFilterBuilder[] filters;

        protected MultipleLogicalOperator(params IFilterBuilder[] filters)
        {
            Argument.NotNull(filters, nameof(filters));

            if (filters.Length < 2)
            {
                throw new ArgumentException("Count of arguments should be greater or equal 2");
            }

            foreach (var item in filters)
            {
                Argument.NotNull(item, nameof(item));
            }

            this.filters = filters;
        }

        public IReadOnlyCollection<IFilterBuilder> Filters
        {
            get
            {
                return this.filters;
            }
        }

        protected abstract string OperatorString { get; }

        public override string Build(IValueSerializer valueSerializer)
        {
            return "("
                   + string.Join(
                       string.Format(Formats.Provider, ") {0} (", this.OperatorString), 
                       this.filters.Select(f => f.Build(valueSerializer))) + ")";
        }
    }
}