using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JtkMainServer.Managers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace JtkMainServer.Pages.MyPage.ChargeCash {
    public class IndexModel : PageModel {
        public string Message { get; set; }

        [BindProperty]
        public Models.ChargeCash ChargeCash { get; set; }

        public IActionResult OnGet() {
            var loginUserId = HttpContext.Session.GetString("LoggedInUserId");
            ViewData["LoggedinUserId"] = loginUserId;
            ViewData["UserTotalCash"] = DbManager.GetUser(loginUserId)?.Cash;
            if (string.IsNullOrWhiteSpace(loginUserId)) {
                // 로그인 안 했을 시, 로그인 페이지로
                HttpContext.Session.SetString("RequestedPage", "MyPage/ChargeCash/Index");
                return RedirectToPage("/Login");
            }
            
            return Page();
        }
        public IActionResult OnPost() {
            var loggedinUserId = HttpContext.Session.GetString("LoggedInUserId");
            ViewData["UserTotalCash"] = DbManager.GetUser(loggedinUserId)?.Cash;
            if (string.IsNullOrWhiteSpace(loggedinUserId)) {
                // 로그인 안 했을 시, 로그인 페이지로
                HttpContext.Session.SetString("RequestedPage", "MyPage/ChargeCash/Index");
                return RedirectToPage("/Login");
            }

            if (ModelState.IsValid == false) {
                // 유효성 검사 불통과 시
                return Page();
            }

            var userTotalCash = DbManager.AdjustUserCash(loggedinUserId, ChargeCash.Amount);
            ViewData["UserTotalCash"] = userTotalCash;
            var now = DateTime.Now;
            DbManager.LogUserCharge(now, loggedinUserId, ChargeCash.Amount, userTotalCash.Value);
            DbManager.LogSaleUserCharge(now, loggedinUserId, ChargeCash.Amount);
            
            HttpContext.Session.SetInt32("ChargedAmount", ChargeCash.Amount);
            return RedirectToPage("./Done");
        }
    }
}