using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Dacryptero.DB;

namespace Dacryptero.Search.AST
{
    public class XorGroup : AstCollectionBase
    {
        public override SearchProgress Check(SearchContext context)
        {
            var result = new List<Collections.TreeCollection<ResultFound>>(Items.Count);
            var score = 0.0;
            bool? feed = null;
            foreach (var item in Items)
            {
                var prog = item.Check(context);
                if (feed is null)
                    feed = prog.IsSuccess;
                else feed ^= prog.IsSuccess;
                result.Add(prog.Previews);
                score += score;
            }
            if (feed is false)
                return new SearchProgress();
            return new SearchProgress(score, new Collections.TreeCollection<ResultFound>(result));
        }

        protected override AstCollectionBase CloneCollection()
        {
            return new XorGroup();
        }

        public override async Task<SearchIndex> GetSearchIndexAsync(DBSingleController db,
            Data.IndexSource source, CancellationToken cancellationToken
        )
        {
            var index = SearchIndex.Empty;
            foreach (var item in Items)
            {
                var entry = await item.GetSearchIndexAsync(db, source, cancellationToken)
                    .ConfigureAwait(false);
                index.UnionWith(entry);
            }
            return index;
        }
    }
}