using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;

namespace IfAnalyzer
{
	[DiagnosticAnalyzer(LanguageNames.CSharp)]
	public class IfAnalyzerAnalyzer : DiagnosticAnalyzer
	{
		public const string DiagnosticId = "IfAnalyzer";

		private static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.AnalyzerTitle), Resources.ResourceManager, typeof(Resources));
		private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.AnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
		private static readonly LocalizableString Description = new LocalizableResourceString(nameof(Resources.AnalyzerDescription), Resources.ResourceManager, typeof(Resources));
		private const string Category = "Naming";

		private static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);

		public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }

		public override void Initialize(AnalysisContext context)
		{
			context.RegisterSyntaxNodeAction(AnalyzeIf, SyntaxKind.IfStatement);
		}

		private static void AnalyzeIf(SyntaxNodeAnalysisContext context)
		{
			var ifNode = (IfStatementSyntax)context.Node;
			var statement = ifNode.Statement;
			if (!(statement is BlockSyntax))
			{
				if (statement is ThrowStatementSyntax)
					return;
				var diagnostic = Diagnostic.Create(Rule, ifNode.Statement.GetLocation());
				context.ReportDiagnostic(diagnostic);
			}
		}
	}
}
