using System.Linq;
using bahnplan.web.database;
using bahnplan.web.database.Tables;
using LinqToDB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace bahnplan.web.Pages {
	public class DeleteModel : PageModel {
		public User AuthorizedUser;

		public void OnGet() {
			if (HttpContext.Session.GetString("authorized") != "true")
				return;

			if (!Request.Query.ContainsKey("confirm") || Request.Query["confirm"] != "true")
				return;

			var       uid = int.Parse(HttpContext.Session.GetString("uid"));
			using var db  = new Database.DbConn();
			AuthorizedUser = db.Users.FirstOrDefault(p => p.UserId == uid);
			var id = int.Parse(Request.Query["id"]);

			switch (Request.Query["item"]) {
				case "trip": {
					var trip = db.Trips.First(p => p.TripId == id);
					if (trip.UserId != int.Parse(HttpContext.Session.GetString("uid")))
						return;

					db.Trips.Delete(p => p.TripId == id);
					db.Legs.Delete(p => p.TripId == id);
					break;
				}
				case "leg": {
					var leg = db.Legs.First(p => p.LegId == id);
					if (leg.UserId != int.Parse(HttpContext.Session.GetString("uid")))
						return;

					var tripid = db.Legs.First(p => p.LegId == id).TripId;

					db.Legs.Delete(p => p.LegId == id);

					if (!db.Legs.Any(p => p.TripId == tripid))
						db.Trips.Delete(p => p.TripId == tripid);
					else if (db.Legs.Where(p => p.TripId == tripid).OrderBy(p => p.DepTime).First().DepTime.EndsWith("placeholder"))
						db.Delete(db.Legs.Where(p => p.TripId == tripid).OrderBy(p => p.DepTime).First());
					else if (db.Legs.Where(p => p.TripId == tripid).OrderByDescending(p => p.DepTime).First().DepTime.EndsWith("placeholder"))
						db.Delete(db.Legs.Where(p => p.TripId == tripid).OrderByDescending(p => p.DepTime).First());
					break;
				}
				case "ticket": {
					var leg = db.Legs.First(p => p.LegId == id);
					if (leg.UserId != int.Parse(HttpContext.Session.GetString("uid")))
						return;

					db.Legs.Where(p => p.LegId == id).Set(p => p.TicketId, 0).Update();
					break;
				}
				case "card": {
					var card = db.Cards.First(p => p.CardId == id);
					if (card.UserId != int.Parse(HttpContext.Session.GetString("uid")))
						return;

					db.Cards.Delete(p => p.CardId == id);
					break;
				}
			}
		}
	}
}