@page
@using LinqToDB
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Http.Extensions
@using Microsoft.AspNetCore.Mvc.TagHelpers
@using trainav.web.Utils
@using trainav.web.database
@model IndexModel
@{
	ViewData["Title"] = "Home";
}

<div class="text-center">
	<h1 class="display-4">
		Welcome, @Model.AuthorizedUser.Username
	</h1>
	<p>
		Here are your planned trips.
	</p>
	<table class="table table-striped">
		<thead>
		<tr>
			<th scope="col">Origin</th>
			<th scope="col">Via</th>
			<th scope="col">Destination</th>
			<th scope="col">Comments</th>
			<th scope="col">Actions</th>
		</tr>
		</thead>
		<tbody>
		@{
			await using var db = new Database.DbConn();
			var trips = db.Trips.Where(p => p.UserId == Model.AuthorizedUser.UserId).ToList();

			foreach (var trip in trips.Where(trip => !db.Legs.Any(p => p.TripId == trip.TripId))) {
				await db.DeleteAsync(trip);
				trips = db.Trips.Where(p => p.UserId == Model.AuthorizedUser.UserId).ToList();
			}

			foreach (var trip in trips.OrderBy(p => db.Legs.Where(a => a.TripId == p.TripId).OrderBy(leg => leg.DepTime).First().DepTime)) {
				var legs = db.Legs.Where(p => p.TripId == trip.TripId).OrderBy(p => p.DepTime).ToList();
				<tr>
					<td>
						<b>@legs.First().DepStation.Delimit(35)</b>
						<br/>
						<small>@DateTime.Parse(legs.First().DepTime).ToString("ddd dd.MM.yyyy, HH:mm")</small>
					</td>
					<td>
						@((from index in from leg in legs where leg.TrainType == "placeholder" select legs.IndexOf(leg) select legs[index - 1].ArrStation.Delimit(35)).ToList().DefaultIfEmpty("-").Aggregate((s1, s2) => $"{s1}, {s2}"))
					</td>
					<td>
						<b>@legs.Last().ArrStation.Delimit(35)</b>
						<br/>
						<small>@DateTime.Parse(legs.Last().ArrTime).ToString("ddd dd.MM.yyyy, HH:mm")</small>
					</td>
					<td>
						@Html.Raw(legs.Where(leg => !string.IsNullOrWhiteSpace(leg.Comment)).Select(p => p.Comment.Replace(", ", "<br/>")).DefaultIfEmpty("").Aggregate((s1, s2) => $"{s1}<br/>{s2}"))
					</td>
					<td>
						<a class="btn btn-sm btn-primary" href="/Trip?id=@trip.TripId">View</a>
						&nbsp;
						<a class="btn btn-sm btn-outline-danger" href="/Delete?item=trip&id=@trip.TripId&redir=@Request.GetDisplayUrl().UrlEncode()">Delete</a>
					</td>
				</tr>
			}
		}
		</tbody>
	</table>
	<br/>
	<div class="d-flex flex-row" style="justify-content: center">
		<div class="d-flex p-2" style="width: 60%">
			<form style="width: 100%" method="GET" action="/OEAPI">
				<h3>Add trip from <a href="https://oeffisear.ch" target="_blank">oeffisear.ch</a> or <a href="https://transit.ztn.sh" target="_blank">transit.ztn.sh</a></h3>
				<br/>
				<div class="input-group">
					<input type="text" class="form-control" name="link" placeholder="paste link / shortcode here">
					<div class="input-group-append">
						<button type="submit" class="btn btn-primary">Submit</button>
					</div>
				</div>
			</form>
		</div>
	</div>
</div>
