using LinqToDB;
using MediaManager.database;
using MediaManager.database.Tables;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace MediaManager.Pages;

public class AddShow : PageModel {
	public User AuthorizedUser;

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

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

		if (!Request.Form.ContainsKey("title")
		 || !Request.Form.ContainsKey("year")
		 || !Request.Form.ContainsKey("watchcount")
		 || !Request.Form.ContainsKey("totaleps")
		 || !Request.Form.ContainsKey("seeneps")
		 || !Request.Form.ContainsKey("status"))
			return;

		var show = new Show {
			UserId        = AuthorizedUser.UserId,
			Title         = Request.Form["title"],
			Year          = int.Parse(Request.Form["year"]),
			WatchCount    = int.Parse(Request.Form["watchcount"]),
			TotalEpisodes = int.Parse(Request.Form["totaleps"]),
			SeenEpisodes  = int.Parse(Request.Form["seeneps"]),
			WatchStatus   = (WatchStatus)int.Parse(Request.Form["status"])
		};

		if (Request.Form.ContainsKey("rating") && !string.IsNullOrEmpty(Request.Form["rating"]))
			show.Rating = int.Parse(Request.Form["rating"]);
		if (Request.Form.ContainsKey("rewatchability") && !string.IsNullOrEmpty(Request.Form["rewatchability"]))
			show.Rewatchability = int.Parse(Request.Form["rewatchability"]);
		if (Request.Form.ContainsKey("lastwatch") && !string.IsNullOrEmpty(Request.Form["lastwatch"]))
			show.LastSeen = DateTime.Parse(Request.Form["lastwatch"]);
		if (Request.Form.ContainsKey("comment") && !string.IsNullOrEmpty(Request.Form["comment"]))
			show.Comment = Request.Form["comment"];

		if (show.SeenEpisodes >= show.TotalEpisodes) {
			show.SeenEpisodes = show.TotalEpisodes;
			if (show.WatchCount == 0)
				show.WatchCount++;
			if (show.WatchStatus != WatchStatus.Waiting)
				show.WatchStatus = WatchStatus.Finished;
		}

		else if (show.SeenEpisodes > 0 && show.WatchStatus == WatchStatus.Unwatched) {
			show.WatchStatus = show.WatchCount == 0 ? WatchStatus.FirstWatch : WatchStatus.Rewatch;
		}

		db.InsertWithIdentity(show);

		Response.Redirect(Request.Form["another"] == "true" ? "/AddShow" : "/Shows");
	}
}
