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 : CsvClassMap<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 csvConfiguration = new CsvConfiguration {IsHeaderCaseSensitive = false};
				csvConfiguration.RegisterClassMap<FluxnetSiteMap>();
				var csvReader = new CsvReader(reader, csvConfiguration);
				return csvReader.GetRecords<FluxnetSite>().ToList();
			}
		}
	}
}
