using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using VEPROMS.CSLA.Library;
using Volian.Base.Library;


namespace VEPROMS
{
	public partial class dlgManageSecurity : Form
	{
		#region Log4Net
		private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		#endregion
		private GroupInfoList myGroupInfoList;
		private UserInfoList myUserInfoList;
		private List<MembershipInfo> myMembershipInfoList;
		private Folder myFolder;
		public dlgManageSecurity()
		{
			InitializeComponent();
		}
		private void dlgManageSecurity_Load(object sender, EventArgs e)
		{
			myFolder = Folder.Get(1);
			SetupSecurity();
			SetupGroups();
		}
		private void SetupGroups()
		{
			pnlGroups.Controls.Clear();
			foreach (GroupInfo gi in myGroupInfoList)
			{
				RadioButton rb = new RadioButton();
				rb.Text = gi.GroupName;
				rb.Parent = pnlGroups;
				rb.Dock = DockStyle.Top;
				rb.Tag = gi;
				rb.CheckedChanged += new EventHandler(rb_CheckedChanged);
				pnlGroups.Controls.Add(rb);
				rb.BringToFront();
				if (myFolder.FolderConfig.Security_Group == 0 && gi.GID == 1)
				{
					myFolder.FolderConfig.Security_Group = gi.GID;
					rb.Checked = true;
					myFolder.Save();
				}
				else if (myFolder.FolderConfig.Security_Group == gi.GID)
				{
					rb.Checked = true;
				}
			}
		}
		private void rb_CheckedChanged(object sender, EventArgs e)
		{
			RadioButton rb = sender as RadioButton;
			GroupInfo gi = rb.Tag as GroupInfo;
			label8.Text = gi.GroupAssignments[0].MyRole.Title + " for " + gi.GroupAssignments[0].MyFolder.Name;
			myFolder.FolderConfig.Security_Group = gi.GID;
			myFolder.Save();
		}
		private void SetupSecurity()
		{
			if (tvFolders.Nodes.Count == 0)
			{
				FolderInfo fi = FolderInfo.Get(1);
				LoadChildFolders(fi, null);
			}
			lstMembers.Items.Clear();
			lstUsers.Items.Clear();
			lstGroups.Items.Clear();
			GroupInfoList.Reset();
			UserInfoList.Reset();
			myGroupInfoList = GroupInfoList.Get();
			myUserInfoList = UserInfoList.Get();
			foreach (GroupInfo gi in myGroupInfoList)
				lstGroups.Items.Add(gi.GroupName);
			lstGroups.SelectedIndex = 0;
			foreach (UserInfo ui in myUserInfoList)
				lstUsers.Items.Add(ui.UserID);
			lstGroups.SelectedIndex = -1;
			lstUsers.SelectedIndex = -1;
		}
		private void LoadChildFolders(FolderInfo fi, TreeNode tn)
		{
			if (tn == null)
			{
				tn = tvFolders.Nodes.Add(fi.Name);
				tn.Tag = fi;
			}
			else
			{
				tn = tn.Nodes.Add(fi.Name);
				tn.Tag = fi;
			}
			if (fi.ChildFolderCount > 0)
			{
				foreach (FolderInfo fic in fi.SortedChildFolders)
				{
					LoadChildFolders(fic, tn);
				}
			}
		}
		private void lstGroups_SelectedIndexChanged(object sender, EventArgs e)
		{
			lblMembers.Text = "Selected Group Users";
			myMembershipInfoList = new List<MembershipInfo>();
			lstMembers.Items.Clear();
			if (lstGroups.SelectedIndex > -1)
			{
				GroupInfo gi = myGroupInfoList[lstGroups.SelectedIndex];
				if (gi.GroupMembershipCount > 0)
					foreach (MembershipInfo mi in gi.GroupMemberships)
					{
						if (mi.EndDate == null || mi.EndDate == string.Empty)
						{
							myMembershipInfoList.Add(mi);
							lstMembers.Items.Add(mi.MyUser.UserID);
						}
					}
			}
		}
		private void addMemberToolStripMenuItem_Click(object sender, EventArgs e)
		{
			int groupIndex = lstGroups.SelectedIndex;
			int userIndex = lstUsers.SelectedIndex;
			GroupInfo gi = myGroupInfoList[groupIndex];
			UserInfo ui = myUserInfoList[userIndex];
			Membership.MakeMembership(User.Get(ui.UID), Group.Get(gi.GID), null, "");
			SetupSecurity();
			if ((sender as ToolStripMenuItem).Name.EndsWith("Group"))
			{
				lstUsers.SelectedIndex = userIndex;
				lstGroups.SelectedIndex = groupIndex;
			}
			else
			{
				lstGroups.SelectedIndex = groupIndex;
				lstUsers.SelectedIndex = userIndex;
			}
		}
		private void removeMemberToolStripMenuItem_Click(object sender, EventArgs e)
		{
			MembershipInfo mi = myMembershipInfoList[lstMembers.SelectedIndex];
			string msg = "Are you sure you want to remove this Group Member?";
			if (MessageBox.Show(this, msg, "Confirm Group Member Removal", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				int groupIndex = lstGroups.SelectedIndex;
				int userIndex = lstUsers.SelectedIndex;
				if (mi.MyGroup.GroupName == "Administrators")
				{
					int k = 0;
					foreach(MembershipInfo mm in mi.MyGroup.GroupMemberships)
						if(mm.EndDate == null || mm.EndDate == string.Empty)
							k++;
					if (k == 1)
					{
						MessageBox.Show("You must have at least 1 user assigned to the Adminstrators group", "One Administrator Required", MessageBoxButtons.OK, MessageBoxIcon.Warning);
						return;
					}
				}
				Membership m = Membership.Get(mi.UGID);
				m.EndDate = DateTime.Now.ToShortDateString();
				m.Save();
				SetupSecurity();
				lstGroups.SelectedIndex = groupIndex;
				lstUsers.SelectedIndex = userIndex;
			}
			//  foreach (int gg in lstGroups.SelectedIndices)
			//  {
			//    GroupInfo gi = myGroupInfoList[gg];
			//    if (gi.GroupName == "Administrators" && gi.GroupMembershipCount == 1)
			//    {
			//      MessageBox.Show("You must have at least 1 user assigned to the Adminstrators group", "Can Not Delete User", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			//      return;
			//    }
			//    foreach (MembershipInfo mi in gi.GroupMemberships)
			//    {
			//      foreach (int mm in lstGroupUsers.SelectedIndices)
			//      {
			//        MembershipInfo mig = myMembershipInfoList[mm];
			//        if (mi.MyUser.UID == mig.MyUser.UID)
			//        {
			//          Membership m = Membership.Get(mi.UGID);
			//          m.EndDate = DateTime.Now.ToShortDateString();
			//          m.Save();
			//        }
			//      }
			//    }
			//  }
			//  SetupSecurity();
			//}
		}
		private void addUserToolStripMenuItem_Click(object sender, EventArgs e)
		{
			User u = User.MakeUser("[Enter New UserID]","", "", "", "", "", "", "", "", "", "",DateTime.Now,"");
			frmManageUser frm = new frmManageUser("add");
			frm.MyUser = u;
			if (frm.ShowDialog(this) == DialogResult.OK)
			{
				u = frm.MyUser;
				u.Save();
				Membership.MakeMembership(u, Group.Get(myFolder.FolderConfig.Security_Group), "", "");
				SetupSecurity();
			}
			else
			{
				u.Delete();
			}
		}
		private void editUserToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (lstUsers.SelectedIndex == -1)
			{
				MessageBox.Show("You must select a user to edit", "No User Selected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				return;
			}
			UserInfo ui = myUserInfoList[lstUsers.SelectedIndex];
			using (User u = User.Get(ui.UID))
			{
				frmManageUser frm = new frmManageUser("edit");
				frm.MyUser = u;
				if (frm.ShowDialog(this) == DialogResult.OK)
				{
					frm.MyUser.Save();
          SetupSecurity();
        }
			}
		}
		private void deleteUserToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (lstUsers.SelectedIndex == -1)
			{
				MessageBox.Show("You must select a user to delete", "No User Selected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				return;
			}
			UserInfo ui = myUserInfoList[lstUsers.SelectedIndex];
			SessionInfoList sil = SessionInfoList.Get();
			foreach (SessionInfo si in sil)
			{
				if (si.UserID == ui.UserID && (si.DTSEnd == null))
				{
					MessageBox.Show("The user selected has an active session.  You may not delete the user at this time.", "User Active Session", MessageBoxButtons.OK, MessageBoxIcon.Warning);
					return;
				}
			}
			int k = 0;
			if (ui.UserMembershipCount > 0)
			{
				foreach (MembershipInfo mi in ui.UserMemberships)
				{
					if (mi.EndDate == null || mi.EndDate == string.Empty)
						k++;
				}
			}
			if (k > 0)
			{
				MessageBox.Show("You must remove user from all groups that user is a member of in order to delete user", "User Has Memberships", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				return;
			}
			if (MessageBox.Show("Are you sure you want to delete this user?", "Confirm Deleting User", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				User.Delete(ui.UID);
				SetupSecurity();
			}
			//to do delete user
			//end date user memberships
			//delete user
		}
		private void createGroupMenuItem(object sender, EventArgs e)
		{
			try
			{
				ToolStripDropDownItem tsddi = sender as ToolStripDropDownItem;
				TreeNode tn = tvFolders.SelectedNode;
				FolderInfo fi = tn.Tag as FolderInfo;
				AddNewGroup(tsddi.Text, fi);
				SetupSecurity();
			}
			catch (Exception ex)
			{
				_MyLog.Warn("createGroupMenuItem", ex);
			}
		}
		private void AddNewGroup(string txt, FolderInfo fi)
		{
			txt = txt.Replace("Create", "").Replace(" a ", "").Replace("Group", "").Trim();
			RoleInfoList ril = RoleInfoList.Get();
			foreach(RoleInfo ri in ril)
			{
				if (ri.Name == txt)
				{
					string gin = string.Format("{0}s - {1}", ri.Name, fi.Name);
					bool addOK = true;
					foreach (GroupInfo gi in myGroupInfoList)
					{
						if (gin == gi.GroupName)
						{
							addOK = false;
							break;
						}
					}
					if (addOK)
					{
						Group group = Group.MakeGroup(gin, null, null);
						Assignment.MakeAssignment(group, Role.Get(ri.RID), Folder.Get(fi.FolderID), null);
					}
				}
			}
			GroupInfoList.Reset();
			myGroupInfoList = GroupInfoList.Get();
			SetupGroups();
		}
		private void lstUsers_SelectedIndexChanged(object sender, EventArgs e)
		{
			lblMembers.Text = "Selected User Groups";
			myMembershipInfoList = new List<MembershipInfo>();
			lstMembers.Items.Clear();
			if (lstUsers.SelectedIndex > -1)
			{
				UserInfo ui = myUserInfoList[lstUsers.SelectedIndex];
				if (ui.UserMembershipCount > 0)
				{
					foreach (MembershipInfo mi in ui.UserMemberships)
					{
						if (mi.EndDate == null || mi.EndDate == string.Empty)
						{
							myMembershipInfoList.Add(mi);
							lstMembers.Items.Add(mi.MyGroup.GroupName);
						}
					}
				}
			}
		}
		private void tvFolders_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
		{
			tvFolders.SelectedNode = e.Node;
		}
		private void deleteGroupToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (lstGroups.SelectedIndex < 0)
			{
				MessageBox.Show("You must select a group to delete", "No Group Selected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				return;
			}
			GroupInfo gi = myGroupInfoList[lstGroups.SelectedIndex];
			if(myFolder.FolderConfig.Security_Group == gi.GID)
			{
				MessageBox.Show("Cannot Delete Default Group", "Attempt to Delete Default", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				return;
			}
			bool deleteOK = true;
			if(gi.GroupMembershipCount > 0)
			{
				foreach (MembershipInfo mi in gi.GroupMemberships)
				{
					if (mi.EndDate == null || mi.EndDate == string.Empty)
					{
						deleteOK = false;
						break;
					}
				}
			}
			if (!deleteOK)
			{
				MessageBox.Show("There are still users who are members of this group.  You need to delete all members in order to delete this group.", "Group Has Members", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				return;
			}
			if (MessageBox.Show("Are you sure you want to delete this group?", "Confirm Deleting Group", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				Group.Delete(gi.GID);
				GroupInfoList.Reset();
				myGroupInfoList = GroupInfoList.Get();
				SetupGroups();
				SetupSecurity();
			}
		}
		private void lstGroups_MouseUp(object sender, MouseEventArgs e)
		{
			lstGroups.SelectedIndex = -1;
			if (e.Button == MouseButtons.Right)
			{
				int k = lstGroups.IndexFromPoint(e.Location);
				if (k >= 0)
				{
					lstGroups.SelectedIndex = k;
					if (lstUsers.SelectedIndex >= 0)
					{
						GroupInfo gi = myGroupInfoList[k];
						if (gi.GroupMembershipCount > 0)
						{
							addMemberToolStripMenuItemGroup.Visible = true;
							UserInfo ui = myUserInfoList[lstUsers.SelectedIndex];
							foreach (MembershipInfo mi in gi.GroupMemberships)
							{
								if (mi.MyUser.UserID == ui.UserID && (mi.EndDate == null || mi.EndDate == string.Empty))
								{
									addMemberToolStripMenuItemGroup.Visible = false;
									break;
								}
							}
						}
					}
					else
						addMemberToolStripMenuItemGroup.Visible = false;
					cmGroups.Show(lstGroups, e.Location);
				}
			}
			else if (e.Button == MouseButtons.Left)
			{
				int k = lstGroups.IndexFromPoint(e.Location);
				if (k >= 0)
				{
					lstGroups.SelectedIndex = k;
				}
			}
		}
		private void lstUsers_MouseUp(object sender, MouseEventArgs e)
		{
			lstUsers.SelectedIndex = -1;
			if (e.Button == MouseButtons.Right)
			{
				int k = lstUsers.IndexFromPoint(e.Location);
				if (k >= 0)
				{
					lstUsers.SelectedIndex = k;
          //addUserToolStripMenuItem.Visible = false;
					editUserToolStripMenuItem.Visible = deleteUserToolStripMenuItem.Visible = true;
					if (lstGroups.SelectedIndex >= 0)
					{
						UserInfo ui = myUserInfoList[k];
						if(ui.UserMembershipCount > 0)
						{
							addMemberToolStripMenuItemUser.Visible = true;
							GroupInfo gi = myGroupInfoList[lstGroups.SelectedIndex];
							foreach(MembershipInfo mi in ui.UserMemberships)
							{
								if (mi.MyGroup.GroupName == gi.GroupName && (mi.EndDate == null || mi.EndDate == string.Empty))
								{
									addMemberToolStripMenuItemUser.Visible = false;
									break;
								}
							}
						}
					}
					else
						addMemberToolStripMenuItemUser.Visible = false;
					cmUsers.Show(lstUsers, e.Location);
				}
				else
				{
					addUserToolStripMenuItem.Visible = true;
					editUserToolStripMenuItem.Visible = deleteUserToolStripMenuItem.Visible = addMemberToolStripMenuItemUser.Visible = false;
					cmUsers.Show(lstUsers, e.Location);
				}
			}
			else if (e.Button == MouseButtons.Left)
			{
				int k = lstUsers.IndexFromPoint(e.Location);
				if (k >= 0)
				{
					lstUsers.SelectedIndex = k;
				}
			}
		}
		private void lstMembers_MouseUp(object sender, MouseEventArgs e)
		{
			lstMembers.SelectedIndex = -1;
			if (e.Button == MouseButtons.Right)
			{
				int k = lstMembers.IndexFromPoint(e.Location);
				if (k >= 0)
				{
					lstMembers.SelectedIndex = k;
					addMemberToolStripMenuItemUser.Visible = false;
					removeMemberToolStripMenuItem.Visible = true;
					cmMembers.Show(lstMembers, e.Location);
				}
				else
				{
					addMemberToolStripMenuItemUser.Visible = true;
					removeMemberToolStripMenuItem.Visible = false;
					cmMembers.Show(lstMembers, e.Location);
				}
			}
			else if (e.Button == MouseButtons.Left)
			{
				int k = lstMembers.IndexFromPoint(e.Location);
				if (k >= 0)
				{
					lstMembers.SelectedIndex = k;
				}
			}
		}
	}
}