// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Shared.Extensions
{
    internal static class DocumentExtensions
    {
        public static bool ShouldHideAdvancedMembers(this Document document)
        {
            var service = document.Project.Solution.Workspace.Services.GetService<IOptionService>();
            return service.GetOption(CompletionOptions.HideAdvancedMembers, document.Project.Language);
        }

        public static async Task<Document> ReplaceNodeAsync<TNode>(this Document document, TNode oldNode, TNode newNode, CancellationToken cancellationToken) where TNode : SyntaxNode
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var newRoot = root.ReplaceNode(oldNode, newNode);
            return document.WithSyntaxRoot(newRoot);
        }

        public static async Task<Document> ReplaceNodesAsync(this Document document,
            IEnumerable<SyntaxNode> nodes,
            Func<SyntaxNode, SyntaxNode, SyntaxNode> computeReplacementNode,
            CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var newRoot = root.ReplaceNodes(nodes, computeReplacementNode);
            return document.WithSyntaxRoot(newRoot);
        }

        public static async Task<IEnumerable<T>> GetUnionResultsFromDocumentAndLinks<T>(
            this Document document,
            IEqualityComparer<T> comparer,
            Func<Document, CancellationToken, Task<IEnumerable<T>>> getItemsWorker,
            CancellationToken cancellationToken)
        {
            var linkedDocumentIds = document.GetLinkedDocumentIds();
            var itemsForCurrentContext = await getItemsWorker(document, cancellationToken).ConfigureAwait(false) ?? SpecializedCollections.EmptyEnumerable<T>();
            if (!linkedDocumentIds.Any())
            {
                return itemsForCurrentContext;
            }

            var totalItems = itemsForCurrentContext.ToSet(comparer);
            foreach (var linkedDocumentId in linkedDocumentIds)
            {
                var linkedDocument = document.Project.Solution.GetDocument(linkedDocumentId);
                var items = await getItemsWorker(linkedDocument, cancellationToken).ConfigureAwait(false);
                if (items != null)
                {
                    totalItems.AddRange(items);
                }
            }

            return totalItems;
        }
    }
}
