using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

namespace OmniSharp.Roslyn.CSharp.Helpers
{
    public static class SyntaxTreeExtensions
    {
        private static readonly string[] _autoGeneratedStrings = new[] { "<autogenerated", "<auto-generated" };

        public static bool IsAutoGenerated(this SyntaxTree syntaxTree, CancellationToken cancellationToken = default)
        {
            SyntaxNode root = syntaxTree.GetRoot(cancellationToken);
            if (!root.HasLeadingTrivia)
            {
                return false;
            }

            SyntaxTriviaList leadingTrivia = root.GetLeadingTrivia();

            foreach (SyntaxTrivia trivia in leadingTrivia)
            {
                if (!IsCommentTrivia(trivia))
                {
                    continue;
                }

                foreach (string autoGenerated in _autoGeneratedStrings)
                {
                    if (!trivia.ToString().Contains(autoGenerated))
                    {
                        continue;
                    }

                    return true;
                }
            }

            return false;
        }

        private static bool IsCommentTrivia(SyntaxTrivia trivia) =>
            trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) ||
            trivia.IsKind(SyntaxKind.SingleLineCommentTrivia) ||
            trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia) ||
            trivia.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia) ||
            trivia.IsKind(SyntaxKind.ShebangDirectiveTrivia);

    }
}
