using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using CsvHelper;
using CsvHelper.Configuration.Attributes;
using Ical.Net.CalendarComponents;
using Ical.Net.DataTypes;
using Ical.Net.Serialization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using trainav.web.database;
using trainav.web.database.Tables;
using Calendar = Ical.Net.Calendar;

namespace trainav.web.Pages;

public class GenIcs : PageModel {
	public     string    IcsOutput;
	public     List<Leg> Legs;
	public new string    User;

	public void OnGet() {
		using var db = new Database.DbConn();

		if (!db.Legs.Any(p => p.TripId == int.Parse(Request.Query["id"]))) {
			IcsOutput = "";
			return;
		}

		Legs = db.Legs.Where(p => p.TripId == int.Parse(Request.Query["id"])).OrderBy(p => p.DepTime).ToList();
		User = db.Users.First(p => p.UserId == Legs.First().UserId).Username;
		if (Request.Query["user"] != User) {
			IcsOutput = "";
			return;
		}

		List<Ds100object> ds100Mapping;

		using (var reader = new StreamReader("ds100.csv"))
			using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) {
				csv.Configuration.Delimiter             = ";";
				csv.Configuration.Encoding              = Encoding.UTF8;
				csv.Configuration.PrepareHeaderForMatch = (header, index) => header.ToLower();
				ds100Mapping                            = csv.GetRecords<Ds100object>().ToList();
			}

		var calendar = new Calendar();
		foreach (var leg in Legs.Where(p => p.TrainType != "placeholder")) {
			var depst = ds100Mapping.Where(p => p.Station == leg.DepStation).DefaultIfEmpty(new Ds100object { Station = leg.DepStation, Ds100 = leg.DepStation }).First().Ds100;
			var arrst = ds100Mapping.Where(p => p.Station == leg.ArrStation).DefaultIfEmpty(new Ds100object { Station = leg.ArrStation, Ds100 = leg.ArrStation }).First().Ds100;
			var title = $"{depst} -> {arrst} ({leg.TrainType} {leg.TrainNr})";
			var e     = new CalendarEvent { Summary = title, Start = new CalDateTime(DateTime.Parse(leg.DepTime)), End = new CalDateTime(DateTime.Parse(leg.ArrTime)) };

			if (!string.IsNullOrWhiteSpace(leg.Comment))
				e.Description = leg.Comment
							  + "\n"
							  + "\n"
							  + $"https://marudor.de/details/{leg.TrainType}{leg.TrainNr}/{DateTime.Parse(leg.DepTime).ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds}000/?station={leg.DepStationId}";

			else
				e.Description =
					$"https://marudor.de/details/{leg.TrainType}{leg.TrainNr}/{DateTime.Parse(leg.DepTime).ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds}000/?station={leg.DepStationId}";

			calendar.Events.Add(e);
		}

		var serializer = new CalendarSerializer();
		IcsOutput = serializer.SerializeToString(calendar);
	}

	private class Ds100object {
		[Name("Bundesland")] public string Bundesland { get; set; }

		[Name("RB")] public string Regionalbereich { get; set; }

		[Name("BM")] public string Bahnhofsmanagement { get; set; }

		[Name("Bf. Nr.")] public string BfNr { get; set; }

		[Name("Station")] public string Station { get; set; }

		[Name("Bf DS 100Abk.")] public string Ds100 { get; set; }

		[Name("Kat. Vst")] public string Kategorie { get; set; }

		[Name("Straße")] public string Strasse { get; set; }

		[Name("PLZ")] public string Plz { get; set; }

		[Name("Ort")] public string Ort { get; set; }

		[Name("Aufgabenträger")] public string Verkehrsverbund { get; set; }
	}
}