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

namespace MediaManager.Pages;

public class AddMovie : 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"))
			return;

		var movie = new Movie { UserId = AuthorizedUser.UserId, Title = Request.Form["title"], Year = int.Parse(Request.Form["year"]), WatchCount = int.Parse(Request.Form["watchcount"]) };

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

		db.InsertWithIdentity(movie);

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