using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;

namespace CSVGenerator
{
	[Generator]
	public class CSVClassesGenerator : ISourceGenerator
	{
		public void Execute(GeneratorExecutionContext context)
		{
			foreach (var item in context.AdditionalFiles)
			{
				if (!".csv".Equals(Path.GetExtension(item.Path), StringComparison.OrdinalIgnoreCase))
					continue;
				var name = Path.GetFileNameWithoutExtension(item.Path);
				var classText = GenerateClassForCSV(item.Path);
				if (classText == null)
					continue;
				context.AddSource($"{name}_Generated.cs", SourceText.From(classText, Encoding.UTF8));
			}
		}

		static string GenerateClassForCSV(string file)
		{
			using (var reader = new StreamReader(file))
			{
				var header = reader.ReadLine();
				var fields = header.Split(new[] { ',' }, StringSplitOptions.None);
				var builder = new StringBuilder();
				builder
					.Append("namespace CSV { public class ")
					.Append(Path.GetFileNameWithoutExtension(file))
					.Append(" { public class Item { ");
				foreach (var item in fields)
				{
					builder
						.Append("public string ")
						.Append(item)
						.Append(" { get; set; } ");
				}
				builder
					.Append("} } }");
				return builder.ToString();
			}
		}

		public void Initialize(GeneratorInitializationContext context)
		{ }
	}
}
