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 UserGroupBasePage : ContractorBasePage
    {
        protected void ProcessRequest(string methodName)
        {
            object result = null;

            try
            {
                if (methodName != null)
                {
                    switch (methodName.ToUpper())
                    {
                        case "GETGROUPS":
                            result = GetGroups();
                            break;
                        case "GETGROUPINFO":
                            result = GetGroupInfo();
                            break;
                        case "SAVEGROUP":
                            result = SaveGroup();
                            break;
                        case "DELETEGROUP":
                            result = DeleteGroup();
                            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; } }

        public UserGroupInfo[] GetGroups()
        {
            var groups = UserManagement.GetGroups().ToArray();
            return groups;
        }

        public GroupDetail GetGroupInfo()
        {
            var iid = Request.Form["ClientData"];
            UserGroupInfo group;
            if (string.IsNullOrEmpty(iid))
            {
                group = new UserGroupInfo();
            }
            else
            {
                Guid guid;
                if (!Guid.TryParse(iid, out guid))
                {
                    throw new ArgumentException("Group ID is not valid.");
                }

                // 返回带 Users 数据的详细用户组对象
                group = UserManagement.GetGroup(guid.ToString());
            }
            var users = UserManagement.GetUsers().OrderBy(u => u.ID).ToArray();

            return new GroupDetail
            {
                GroupInfo = group,
                Users = users
            };
        }

        public string SaveGroup()
        {
            var content = Request.Form["ClientData"];
            content = HttpUtility.HtmlDecode(content);
            var item = JsonConvert.DeserializeObject<UserGroupInfo>(content);

            // 保存组基本信息,与包含的全部用户
            if (string.IsNullOrWhiteSpace(item.Name))
            {
                throw new ArgumentException("Group Name cannot be empty.");
            }
            item.Name = item.Name.Trim();
            if (string.IsNullOrEmpty(item.ID))
            {
                // add
                item.ID = Guid.NewGuid().ToString();
                UserManagement.AddGroup(item);
            }
            else
            {
                UserManagement.UpdateGroup(item);
            }
            return "";
        }

        public string DeleteGroup()
        {
            var iid = Request.Form["ClientData"];
            Guid guid;
            if (!Guid.TryParse(iid, out guid))
            {
                throw new ArgumentException("Group ID is not valid.");
            }
            try
            {
                UserManagement.DeleteGroup(guid.ToString());
                return "";
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("Error", "DeleteGroup", ex.Message, ex.ToString());
                throw ex;
            }
        }
    }

    public class GroupDetail
    {
        public UserGroupInfo GroupInfo { get; set; }
        public UserInfo[] Users { get; set; }
    }
}