using IronIntel.Contractor.Users;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace IronIntel.Contractor.Site.Security
{
    public class DataTablePermissionBasePage : ContractorBasePage
    {
        protected void ProcessRequest(string methodName)
        {
            object result = null;

            try
            {
                if (methodName != null)
                {
                    switch (methodName.ToUpper())
                    {
                        case "GETUSERS":
                            result = GetUsers();
                            break;
                        case "GETUSERGROUPS":
                            result = GetUserGroups();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
                SystemParams.WriteLog("Error", "UserGroupBasePage.ProcessRequest", ex.Message, ex.ToString());
            }

            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }

        protected override bool AllowCurrentLoginSessionEnter()
        {
            var f = base.AllowCurrentLoginSessionEnter();
            if (!f)
            {
                return false;
            }

            // check whether you are admin.
            var session = GetCurrentLoginSession();
            if (session == null || session.User == null)
            {
                return false;
            }
            var ui = UserManagement.GetUserByIID(session.User.UID);
            return ui != null && ui.UserType >= UserTypes.Admin;
        }

        protected override bool ThrowIfNotAllowed { get { return true; } }

        private UserInfo[] GetUsers()
        {
            var users = UserManagement.GetUnmanagementUsers().OrderBy(u => u.DisplayName).ToArray();
            return users;
        }

        private UserGroupInfo[] GetUserGroups()
        {
            var groups = UserManagement.GetGroups();
            return groups;
        }
    }
}