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

namespace MediaManager.Pages;

public class EditMovie : PageModel {
	public User AuthorizedUser;

	public void OnGet() {
		using var db      = new Database.DbConn();
		var       movieId = int.Parse(RouteData.Values["id"]!.ToString()!);
		var       movie   = db.Movies.First(p => p.MovieId == movieId);

		AuthorizedUser = db.Users.FirstOrDefault(p => p.Username == AuthUtil.GetRemoteUser(HttpContext, db))!;

		if (movie.UserId != AuthorizedUser.UserId)
			Response.Redirect("/");
	}

	public void OnPost() {
		using var db      = new Database.DbConn();
		var       movieId = int.Parse(RouteData.Values["id"]!.ToString()!);
		var       movie   = db.Movies.First(p => p.MovieId == movieId);

		AuthorizedUser = db.Users.FirstOrDefault(p => p.Username == AuthUtil.GetRemoteUser(HttpContext, db))!;

		if (movie.UserId != AuthorizedUser.UserId) {
			Response.Redirect("/");
			return;
		}

		if (Request.Form["action"] == "delete") {
			db.Delete(movie);
			Response.Redirect("/Movies");
			return;
		}

		if (Request.Form["action"] == "autoinc") {
			movie.WatchCount++;
			movie.LastSeen = DateTime.Now;

			db.Update(movie);
			Response.Redirect($"/Movies#movie_{movie.MovieId}");
			return;
		}

		movie.Title          = Request.Form["title"];
		movie.Year           = int.Parse(Request.Form["year"]);
		movie.WatchCount     = int.Parse(Request.Form["watchcount"]);
		movie.Rating         = int.Parse(Request.Form["rating"]);
		movie.Rewatchability = int.Parse(Request.Form["rewatchability"]);
		movie.LastSeen       = string.IsNullOrEmpty(Request.Form["lastwatch"]) ? DateTime.MinValue : DateTime.Parse(Request.Form["lastwatch"]);
		movie.Comment        = Request.Form["comment"];

		db.Update(movie);

		Response.Redirect($"/Movies#movie_{movie.MovieId}");
	}
}
