using System;
using System.Diagnostics.CodeAnalysis;
using CsvHelper.Configuration;
using CsvHelper;
using System.Globalization;
using Splat;
using StarsAssistant.Services;
namespace StarsAssistant.CSV;
public class PlanetLoader
{
    /// 
    /// Reference to the game metadata, retrieved by DI
    /// 
    protected Services.Game Game = Locator.Current.GetService()!;
    /// 
    /// CSV Configuration to use for importing Planet files.
    /// 
    protected CsvConfiguration CsvConfig;
    /// 
    /// Construction
    /// 
    public PlanetLoader()
    {
        CreateConfig();
    }
    /// 
    /// Creates the CSV configuration for planets.
    /// 
    [MemberNotNull(nameof(CsvConfig))]
    protected void CreateConfig() 
    {
        CsvConfig = CsvConfiguration.FromAttributes(CultureInfo.InvariantCulture);
        CsvConfig.Delimiter = "\t";
        CsvConfig.Escape = '\0';
        CsvConfig.MissingFieldFound = null;
    }
    /// 
    /// Import the planet file for the given Race.
    /// 
    /// Import File
    public void ImportForRace(Model.Race race)
    {
        using var db = Locator.Current.GetService()!;
        using var reader = new StreamReader(Game.PlanetFileForRace(race), System.Text.Encoding.Latin1);
        using var csv = new CsvReader(reader, CsvConfig);
        List records = csv.GetRecords().ToList();
        var planetByPlayer = from csvp in records
                             group csvp by csvp.Owner into byOwners
                             select byOwners;
        foreach (var owner in planetByPlayer)
        {
            Model.Race? r;
            if (owner.Key == race.Name)
            {
                r = race;
            }
            else
            {
                r = db.Race.Find(owner.Key);
                if (r == null)
                {
                    r = new() { Name = owner.Key };
                    db.Add(r);
                }
            }
            foreach (Planet csvp in owner)
            {
                Model.Planet? p = db.Planet.Find(csvp.Name);
                if (p == null)
                {
                    p = new() { Name = csvp.Name };
                    csvp.UpdateDbPlanet(p);
                    db.Add(p);
                }
                else
                {
                    csvp.UpdateDbPlanet(p);
                    db.Update(p);
                }
            }
            db.SaveChanges();
        }
    }
}