using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LocalizerGenerator
{
	class RegistrationsBuilder
	{
		public string Namespace { get; set; }
		public List<LocalizerBuilder> Localizers { get; } = new List<LocalizerBuilder>();
		public string MethodName => "AddGeneratedResourceWrappers";

		public string BuildSource()
		{
			var builder = new StringBuilder();
			BuildNamespace(builder);
			return builder.ToString();
		}

		void BuildNamespace(StringBuilder builder)
		{
			builder.Append("namespace ").Append(Namespace).Append(" {").AppendLine();
			BuildUsings(builder);
			BuildClass(builder);
			builder.AppendLine("}");
		}

		void BuildUsings(StringBuilder builder)
		{
			builder.AppendLine("using Microsoft.Extensions.DependencyInjection;");
			builder.AppendLine("using Microsoft.Extensions.Localization;");
			foreach (var @namespace in Localizers.Select(x => x.Namespace).Distinct(StringComparer.Ordinal))
			{
				builder.Append("using ").Append(@namespace).Append(";").AppendLine();
			}
		}

		void BuildClass(StringBuilder builder)
		{
			builder.Append("partial class ").Append(LocalizerGenerator.ServiceCollectionInstallerMarker).Append(" {").AppendLine();
			builder.Append("public static void ").Append(MethodName).Append("(IServiceCollection services) {").AppendLine();
			BuildRegistrations(builder);
			builder.AppendLine("}");
			builder.AppendLine("}");
		}

		void BuildRegistrations(StringBuilder builder)
		{
			foreach (var localizer in Localizers)
			{
				builder.Append("services.AddScoped<").Append(localizer.IStringLocalizerName).Append(", ").Append(localizer.ClassName).Append(">();").AppendLine();
			}
		}
	}
}
