using System.Text.RegularExpressions;
using Core.Entities;

namespace Core.Parsers;

public class EventDefinitionParser : CsvParserBase
{
    public EventDefinitionParser(FileSystemInfo csvFile, bool ignoreBlankLines = true) : base(csvFile, ignoreBlankLines)
    {
    }

    public EventDefinitionParser(StreamReader reader, bool ignoreBlankLines = true) : base(reader, ignoreBlankLines)
    {
    }

    public EventDefinition[] Parse()
    {
        var events = new List<EventDefinition>();

        CsvReader.Read();
        CsvReader.ReadHeader();

        while (CsvReader.Read())
		{
			var name = CsvReader.GetField("Event");
			if (string.IsNullOrEmpty(name))
				continue;
			var shortName = CsvReader.GetField("Short Name");

			Enum.TryParse(CsvReader.GetField("EventFormat"), out EventFormat format);

			var teamSize = CsvReader.GetField("Team Size");
			if (string.IsNullOrEmpty(teamSize))
				throw new ArgumentException(@"Team Size is null for {name}");
			var match = Regex.Match(teamSize, @"(\d)(?:\s?to\s?)?(\d)?");
			var min = int.Parse(match.Groups[1].Captures[0].Value);
			var max = match.Groups[2].Success ? int.Parse(match.Groups[2].Captures[0].Value) : min;

			var stateTeams = CsvReader.GetField<int>("State Count");
			var semifinalistActivity = CsvReader.GetField("Semifinalist Activity");
			var regionalCount = CsvReader.GetField("Regional Count");
			var regionalPresubmit = CsvReader.GetField("Regional Presubmission");
			var statePresubmission = CsvReader.GetField("State Presubmission");
			var statePretesting = CsvReader.GetField("State Pretesting");
			var statePreliminary = CsvReader.GetField("State Preliminary Round");
			var regionalNotes = CsvReader.GetField("Regional Notes");
			var documentation = CsvReader.GetField("Documentation");
			var eligibility = CsvReader.GetField("Eligibility");
			var theme = CsvReader.GetField("Theme");
			var description = CsvReader.GetField("Description");
			var levelOfEffort = CsvReader.GetField<int?>("Level of Effort");
			//var regionalTeams = CsvReader.GetField<int>("Regional TimeSlots");

			var competitiveEvent = new EventDefinition
			{
				Name = name.Trim(), 
				ShortName = shortName.Trim(), 
				EventFormat = format,
				ChapterEligibilityCountState = stateTeams,
				MinTeamSize = min,
				MaxTeamSize = max,
				SemifinalistActivity = semifinalistActivity,
				//RegionalEvent = !string.IsNullOrEmpty(regionalCount),
				//RegionalPresubmit = regionalPresubmit.Trim() == "TRUE",
				Notes = regionalNotes,
				Documentation= documentation,
				Presubmission = statePresubmission.Trim() == "TRUE",
				//StatePretesting = statePretesting.Trim() == "TRUE",
				//StatePreliminaryRound = statePreliminary.Trim() == "TRUE",
				Eligibility = eligibility,
				Theme = theme,
				Description = description,
				LevelOfEffort = levelOfEffort
			};
			events.Add(competitiveEvent);
        }

        return events.ToArray();
    }
}