using System;
using System.Collections.Generic;
using System.Linq;
using Valg.EVA.Skanning.ServicesModel.ElectionConfig.Model;

namespace Valg.EVA.Skanning.ServicesModel.ElectionConfig.DataProvider
{
    public class MunicipalitiesCsvReader : IMunicipalitiesCsvReader
    {
        public List<County> ReadCounties(string municipalitiesCsv)
        {
            return GetLines(municipalitiesCsv)
                .Select(GetCounty)
                .Distinct()
                .ToList();
        }

        public List<Municipality> ReadMunicipalities(string municipalitiesCsv)
        {
            return GetLines(municipalitiesCsv)
                .Select(GetMunicipality)
                .ToList();
        }

        private static County GetCounty(string line)
        {
            var values = line.Split(',');
            return new County { Code = values[2], Name = values[3] };
        }

        private Municipality GetMunicipality(string line)
        {
            var values = line.Split(',');
            return new Municipality { Code = values[4], Name = values[5], CountyCode = values[2], CountyName = values[3] };
        }

        private static IEnumerable<string> GetLines(string municipalitiesCsv)
        {
            return municipalitiesCsv.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }
    }
}
