using System.Collections.Generic;
using System.Linq;
using LinqToDB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using trainav.web.database;
using trainav.web.database.Tables;
using trainav.web.Utils;

namespace trainav.web.Pages;

public class TripModel : PageModel {
	public     List<Leg> Legs;
	public     bool      RedirToIndex;
	public     User      AuthorizedUser;
	public new string    User;

	public void OnGet() {
		using var db = new Database.DbConn();
		AuthorizedUser = db.Users.FirstOrDefault(p => p.Username == AuthUtil.GetRemoteUser(HttpContext, db));

		if (Request.Query.ContainsKey("separator")) {
			var leg = db.Legs.First(p => p.LegId == int.Parse(Request.Query["legid"]));
			if (leg.UserId != AuthorizedUser!.UserId)
				return;

			db.Insert(new Leg {
				TripId       = int.Parse(Request.Query["id"]),
				UserId       = AuthorizedUser.UserId,
				TrainType    = "placeholder",
				TrainNr      = int.Parse(Request.Query["legid"]),
				ArrStation   = "_",
				ArrStationId = 0,
				ArrTime      = "_",
				DepStation   = "_",
				DepStationId = 0,
				DepTime      = leg.DepTime + "_placeholder"
			});
			return;
		}

		Legs = db.Legs.Where(p => p.TripId == int.Parse(Request.Query["id"])).OrderBy(p => p.DepTime).ToList();

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

		User = db.Users.First(p => p.UserId == Legs.First().UserId).Username;
	}

	public void OnPost() {
		using var db = new Database.DbConn();
		if (!Request.Form.ContainsKey("comment"))
			return;

		var leg = db.Legs.First(p => p.LegId == int.Parse(Request.Form["id"]));
		if (leg.UserId != AuthorizedUser.UserId)
			return;

		leg.Comment = Request.Form["comment"];

		db.Update(leg);
	}
}
