using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;
using Quizzer.Extensions;
using Quizzer.Implementations;
using Quizzer.Models;
using Quizzer.OpenIDConnect;
using Quizzer.Persistens;
using System.IdentityModel.Tokens.Jwt;

namespace Quizzer.Pages
{
    public class QuizzesModel : PageModel
    {
        [BindProperty]
        public OpenIDUCNData ucnData { get; set; }

        [BindProperty]
        public string UserID { get; set; }

        [BindProperty]
        public List<QuizzDN> QuizzList { get; set; }

        [BindProperty]
        public string CategorySelect { get; set; }

        [BindProperty]
        public List<string> TheClassList { get; set; }

        [BindProperty]
        public Quizz pageQuizz { get; set; }

        [BindProperty]
        public string myFullName { get; set; }


        private bool isDebug;
        private string KCUserID { get; set; }

        private DbOps dbManager = new();
        private OpenIDConnectUtils OpenIDUtils = new();
        private Quizz quizzCookie;

        public void Common()
        {
            isDebug = MyConfiguration.Get()["DEBUG"] == "Y";
            string? ucnDataJson = OpenIDUtils.GetJwtClaim(HttpContext, "ucn");

            KCUserID = OpenIDUtils.GetJwtClaim(HttpContext, "sub");
            ucnData = JsonConvert.DeserializeObject<OpenIDUCNData>(ucnDataJson);
            UserID = OpenIDUtils.GetJwtClaim(HttpContext, "email").HashSHA256();
            myFullName = OpenIDUtils.GetJwtClaim(HttpContext, "name");
        }

        private void GetMyCookie()
        {
            string jsonString = HttpContext.Request.Cookies["quizzCookie"];
            if (jsonString != null)
            {
                quizzCookie = JsonConvert.DeserializeObject<Quizz>(jsonString);
                return;
            }
            // Here if no cookie found
            quizzCookie = new Quizz
            {
                Category = "",
                Class = "",
                Anonymous = false,
                Descr = "",
                QSize = 5,
                QuizzId = "",
            };
            // Save the new cookie
            SetMyCookie();
        }

        private void SetMyCookie()
        {
            string jsonResult = JsonConvert.SerializeObject(quizzCookie);
            Response.Cookies.Append("quizzCookie", jsonResult, new Microsoft.AspNetCore.Http.CookieOptions
            {
                Secure = true,
                HttpOnly = true,
                SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None,
            });
        }

        private void RemoveMyCookie()
        {
            Response.Cookies.Delete("quizzCookie");
        }

        public IActionResult OnGet()
        {
            Common();
            if (ucnData.theRole != "teacher" && ucnData.theRole != "developer") return Redirect("/");
            GetMyCookie();
            pageQuizz = JsonConvert.DeserializeObject<Quizz>(JsonConvert.SerializeObject(quizzCookie));
            QuizzList = dbManager.GetQuizzesTeacher(UserID);
            CategorySelect = dbManager.MakeCList(UserID, "DropDownIndented", quizzCookie.Category);
            TheClassList = new();
            KeyCloak KCApi = new KeyCloak();
            List<KCGroups> myGroups = KCApi.KeyCloakGetUsersGroups(KCUserID);
            foreach (var group in myGroups)
            {
                if (group.name.Contains("-CSD-")) TheClassList.Add(group.name);
            }
            return Page();
        }
        public IActionResult OnPost(string action = "na", string categoryParent = "", string newCategory = "na", string target = "na")
        {
            Common();
            GetMyCookie();
            //tagPath = JsonConvert.DeserializeObject<List<Tags>>(theTagPath);
            switch (action)
            {
                case "createQuizz":
                    quizzCookie.Descr = pageQuizz.Descr;
                    quizzCookie.Anonymous = pageQuizz.Anonymous;
                    quizzCookie.QSize = pageQuizz.QSize;
                    quizzCookie.Owner = UserID;
                    dbManager.InsertQuizz(quizzCookie);
                    break;
                case "changeCategory":
                    quizzCookie.Category = newCategory;
                    break;
                case "changeClass":
                    pageQuizz.Class = quizzCookie.Class = target;
                    break;
                case "delete":
                    dbManager.DeleteQuizz(target);
                    dbManager.DeleteStatistics(target);
                    dbManager.DeleteJournalByQuizz(target);
                    break;
                case "na":
                    if (newCategory != "na") quizzCookie.Category = newCategory;
                    break;
                default:
                    break;
            }
            SetMyCookie();
            return Redirect("/Quizzes");
        }
    }
}
