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

namespace JtkMainServer.Pages.Manage {
    public class RegisterPartnerModel : PageModel {
        public string ErrorMessage { get; set; }
        public string Message { get; set; }

        [BindProperty]
        public Models.RegisterPartner RegisterPartner { get; set; } = new RegisterPartner();

        [BindProperty]
        public Models.PaymentTime PaymentTime { get; set; } = new PaymentTime() { Time="12:00" };

        public IActionResult OnGet() {
            var userId = HttpContext.Session.GetString("LoggedInUserId");
            if (string.IsNullOrWhiteSpace(userId)) {
                // 로그인 안 했을 시, 로그인 페이지로
                HttpContext.Session.SetString("RequestedPage", "Manage/RegisterPartner");
                return RedirectToPage("/Login");
            }
            if (userId != "admin") {
                return RedirectToPage("/Index");
            }
            
            //PaymentTime.Time = $"{place.PaymentHour:00}:{place.PaymentMinute:00}";
            //PaymentTime.AccountNumber = place.AccountNumber;

            return Page();
        }
        public IActionResult OnPost(IFormFile file) {
            /*if (HttpContext.Request.Query.TryGetValue("id", out var placeIds) == false || placeIds.Count < 1) {
                return RedirectToPage("./Partners");
            }
            var placeId = placeIds[0];

            var hour = int.Parse(PaymentTime.Time.Substring(0, 2));
            var minute = int.Parse(PaymentTime.Time.Substring(3, 2));
            if (DbManager.SetPlacePaymentTime(placeId, hour, minute, PaymentTime.AccountNumber)) {
                Message = $"변경되었습니다.";
            } else {
                Message = "실패";
            }
            */
            if (ModelState.IsValid == false) {
                // 유효성 검사 불통과 시
                Console.WriteLine("불통과!");
                return Page();
            }
            Message = "";
            ErrorMessage = "";
            var hour = int.Parse(PaymentTime.Time.Substring(0, 2));
            var minute = int.Parse(PaymentTime.Time.Substring(3, 2));
            if (DbManager.AddPlace(RegisterPartner.Id, RegisterPartner.Password, RegisterPartner.Name, RegisterPartner.Location.Trim(' ', '(', ')'), RegisterPartner.Address, RegisterPartner.Introduction, hour, minute, PaymentTime.AccountNumber, PaymentTime.Royalty)) {
                Message = "성공적으로 등록되었습니다.";
                return RedirectToPage("./RegisteredPartner");
            } else {
                ErrorMessage = "등록에 실패하였습니다.";
                ViewData["Location"] = RegisterPartner.Location;
            }
            
            return OnGet();
        }
    }
}
