﻿/*
 * SonarAnalyzer for .NET
 * Copyright (C) 2015-2017 SonarSource SA
 * mailto: contact AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

using System;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;

namespace SonarAnalyzer.Helpers
{
    public abstract class GeneratedCodeRecognizer
    {
        public virtual bool IsGenerated(SyntaxTree tree)
        {
            return HasGeneratedFileName(tree) ||
                HasAutoGeneratedComment(tree) ||
                HasGeneratedCodeAttribute(tree);
        }

        private static readonly string[] GeneratedFileParts =
            {
                ".G.",
                ".GENERATED.",
                ".DESIGNER.",
                "_GENERATED.",
                "TEMPORARYGENERATEDFILE_"
            };
        private static readonly string[] AutoGeneratedCommentParts =
            {
                "<AUTO-GENERATED",
                "<AUTOGENERATED"
            };
        private static readonly string[] GeneratedCodeAttributes =
            {
                "DebuggerNonUserCode",
                "DebuggerNonUserCodeAttribute",
                "GeneratedCode",
                "GeneratedCodeAttribute",
                "ExcludeFromCodeCoverage",
                "ExcludeFromCodeCoverageAttribute",
                "CompilerGenerated",
                "CompilerGeneratedAttribute"
            };

        private static bool HasGeneratedFileName(SyntaxTree tree)
        {
            if (string.IsNullOrEmpty(tree.FilePath))
            {
                return false;
            }

            var fileName = Path.GetFileName(tree.FilePath).ToUpperInvariant();
            return GeneratedFileParts.Any(part => fileName.Contains(part));
        }

        private bool HasAutoGeneratedComment(SyntaxTree tree)
        {
            var root = tree.GetRoot();
            if (root == null)
            {
                return false;
            }

            var firstToken = root.GetFirstToken(true);

            if (!firstToken.HasLeadingTrivia)
            {
                return false;
            }

            var trivia = firstToken.LeadingTrivia;

            var comments = trivia.Where(IsTriviaComment);
            return comments.Any(t =>
            {
                var commentText = t.ToString().ToUpperInvariant();
                return AutoGeneratedCommentParts.Any(part => commentText.Contains(part));
            });
        }

        private bool HasGeneratedCodeAttribute(SyntaxTree tree)
        {
            var attributeNames = tree.GetRoot()
                .DescendantNodesAndSelf()
                .Select(GetAttributeName)
                .Where(name => !string.IsNullOrEmpty(name));

            return attributeNames.Any(attributeName =>
                GeneratedCodeAttributes.Any(generatedCodeAttribute =>
                    attributeName.EndsWith(generatedCodeAttribute, StringComparison.Ordinal)));
        }

        protected abstract bool IsTriviaComment(SyntaxTrivia trivia);
        protected abstract string GetAttributeName(SyntaxNode node);
    }
}
