using ClassSelect.Implementations;
using ClassSelect.Models;
using ClassSelect.OpenIDConnect;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;
using System.Collections;
using System.IdentityModel.Tokens.Jwt;


namespace ClassSelect.Pages
{
    public class IndexModel : PageModel
    {
        [BindProperty]
        public List<KCGroups>? availableGroups { get; set; }

        [BindProperty]
        public OpenIDUCNData? ucnData { get; set; }

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

        [BindProperty]
        public List<KCGroups> currentGroups { get; set; }

        [BindProperty]
        public bool isTeacher { get; set; }

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

        private OpenIDConnectUtils OpenIDUtils = new();

        private readonly ILogger<IndexModel> _logger;

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// Loads available Jeycloak groups, and authorizes user.
        /// </summary>
        /// <param name="keyCloak"></param>
        private void LoadIdFromAccesstoken(KeyCloak keyCloak)
        {
            // load available groups from keycloak
            availableGroups = keyCloak.KeyCloakGetGroups();
            KCUserID = OpenIDUtils.GetJwtClaim(HttpContext, "sub");
            string? ucnDataJson = OpenIDUtils.GetJwtClaim(HttpContext, "ucn");
            if (ucnDataJson != null)
            {
                // the ucn section is available, but is it safe?
                ucnData = JsonConvert.DeserializeObject<OpenIDUCNData>(ucnDataJson);
                if (ucnData.theRole == null) ucnDataJson = null;
            }
            if (ucnDataJson == null)
            {
                string email = OpenIDUtils.GetJwtClaim(HttpContext, "email");
                Console.WriteLine("New entity: " + email);
                // Lets try to determine if student or teacher. All emails starting with a digit is a student, kajestud is a student. Others are teachers
                if (email[0] >= '0' && email[0] <= '9')
                {
                    // Student
                    keyCloak.KeyCloakJoinGroup(KCUserID, keyCloak.KeyCloakStudent());
                    keyCloak.KeyCloakJoinGroup(KCUserID, keyCloak.KeyCloakClassLess());
                    ucnData.theClass = new();
                    ucnData.theClass.Add("Please select your class");
                    ucnData.theRole = "student";
                    isTeacher = false;
                }
                else
                {
                    // Teacher
                    keyCloak.KeyCloakJoinGroup(KCUserID, keyCloak.KeyCloakTeacher());
                    ucnData.theClass = new();
                    ucnData.theRole = "teacher";
                    isTeacher = true;
                }
            }
            else
            {
                // the ucn section is available
                ucnData = JsonConvert.DeserializeObject<OpenIDUCNData>(ucnDataJson);
                if (isDebug) Console.WriteLine("userID=[{0}]  ucnDataJson=[{1}]", KCUserID, ucnDataJson);
            }
        }

        public void Common()
        {
            isDebug = MyConfiguration.Get()["DEBUG"] == "Y";
            KeyCloak keyCloak = new();
            LoadIdFromAccesstoken(keyCloak);
            currentGroups = keyCloak.KeyCloakGetUsersGroups(KCUserID);  //loads isTeacher value
            isTeacher = keyCloak.KeyCloakIsTeacher();
            if (isDebug)
            {
                Console.WriteLine("currentGroups.Count= " + currentGroups.Count.ToString());
                if (isTeacher) Console.WriteLine("TEACHER"); else Console.WriteLine("STUDENT");
                foreach (KCGroups item in currentGroups)
                {
                    Console.WriteLine("Member of: " + item.name);
                }
            }
            isTeacher = keyCloak.KeyCloakIsTeacher();
        }


        public void OnGet()
        {
            if (isDebug) Console.WriteLine("OnGet...");
            Common();
            if (isDebug) Console.WriteLine("OnGet...Done");
        }

        public IActionResult OnPost(string action = "ERR", string target = "ERR")
        {
            KeyCloak keyCloak = new();
            Common();
            if (isDebug) Console.WriteLine("OnPost [{0}] [{1}]", action, target);
            if (action == "selectclass")
            {
                // Get the groups for this user
                List<KCGroups> myGroups = keyCloak.KeyCloakGetUsersGroups(KCUserID);
                if (isDebug) Console.WriteLine("Student: {0}", KCUserID);
                if (action == "selectclass") // Students can only be associated to one class
                {
                    keyCloak.KeyCloakLeaveGroup(KCUserID, keyCloak.KeyCloakClassLess());
                    foreach (KCGroups group in myGroups)
                        if (group.name.Contains("-CSD-"))
                        {
                            keyCloak.KeyCloakLeaveGroup(KCUserID, group.id);
                            if (isDebug) Console.WriteLine("{0} leaving {1}:{2}", KCUserID, group.id, group.name);
                        }
                }
                keyCloak.KeyCloakJoinGroup(KCUserID, target);
            }
            if (action == "toggleclass")
            {
                if (isTeacher)
                {
                    if (isDebug) Console.WriteLine("toggleclass: Teacher: [{0}] [{1}]", KCUserID, target);
                    keyCloak.KeyCloakToggleMembership(KCUserID, target);
                }
                else
                {
                    if (isDebug) Console.WriteLine("MUST BE TEACHER TO DO THIS");
                }
            }
            if (isTeacher)
            {
                if (action == "logout") return Redirect("https://auth.a.ucnit.eu/realms/UCNit/protocol/openid-connect/logout");
                return Redirect("/");
            }
            return Redirect("https://auth.a.ucnit.eu/realms/UCNit/protocol/openid-connect/logout");
        }
    }
}