using System.Collections.Generic;
using System.IO;
using System.Linq;
using CsvHelper;
using CsvHelper.Configuration;
using LeafWeb.Core.Entities;

namespace LeafWeb.Core.Parsers
{
	public class FluxnetSiteCsvParser
	{
		private readonly FileSystemInfo _csvFile;

		private sealed class FluxnetSiteMap : ClassMap<FluxnetSite>
		{
			public FluxnetSiteMap()
			{
				Map(m => m.FluxnetId);
				Map(m => m.SiteName);
				Map(m => m.Country);
				Map(m => m.LandUnit).Name("land_unit");
			}
		}

		public FluxnetSiteCsvParser(FileSystemInfo csvFile)
		{
			_csvFile = csvFile;
		}

		public IList<FluxnetSite> Parse()
		{
			using (var reader = CsvParserBase.OpenCsv(_csvFile))
			{
				var csvReader = new CsvReader(reader);
                csvReader.Configuration.PrepareHeaderForMatch = (s, i) => s.ToLowerInvariant();
                csvReader.Configuration.RegisterClassMap<FluxnetSiteMap>();
				return csvReader.GetRecords<FluxnetSite>().ToList();
			}
		}
	}
}
