using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;
using digioz;

public partial class controls_admin_UserManagement : System.Web.UI.UserControl
{
    private List<User> coUserList;
    private const string csFilterMode = "FilterMode";

    enum FilterMode
    {
        ByName,
        ByEmail
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            multiViewUserManager.ActiveViewIndex = 1;
        }

        setDataOnLoad();
    }

    protected override void OnPreRender(EventArgs e)
    {
        if (Context.Session != null && Context.Session.IsNewSession)
        {
            string sCookieHeader = Page.Request.Headers["Cookie"];
            if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
            {
                Session["CurrentUser"] = null;
            }
        }

        txtPassword.Attributes.Add("value", txtPassword.Text);
        if (CustomValidator4 != null && !CustomValidator4.IsValid)
            tbChangePassword.Attributes.Add("value", tbChangePassword.Text);
        else
        {
            tbChangePassword.Attributes.Add("value", "");
        }

        base.OnPreRender(e);
    }

    private void setDataOnLoad()
    {
        if (isViewActive(this.viewUsers))
        {
            lblListUserMessage.Text = "";
            setListUserData();
        }
        if (isViewActive(viewEditUserProfile))
        {
            this.lblEditUserProfileMsg.Text = "";
        }

        if (isViewActive(viewEditUserProfilePassword))
        {
            this.lblPasswordMessage.Text = "";
        }
        if (isViewActive(viewEditUserProfilePermission))
        {
            this.lblPermissionMsg.Text = "";
        }
    }

    private bool isViewActive(View pView)
    {
        if (multiViewUserManager.ActiveViewIndex >= 0 && multiViewUserManager.Views != null)
        {
            return multiViewUserManager.Views[multiViewUserManager.ActiveViewIndex] == pView;
        }
        return false;
    }

    public void activateViewListUsers()
    {
        activateView(this.viewUsers);
        this.UserManagerMenu.Items[1].Selected = true;
    }

    private void activateView(View pView)
    {
        int index = multiViewUserManager.Views.IndexOf(pView);
        if (index >= 0)
        {
            multiViewUserManager.ActiveViewIndex = index;
        }
    }
    protected void doOnPageMenuClick(object sender, MenuEventArgs e)
    {

        int index = Int32.Parse(e.Item.Value);
        userProfileMenu.Visible = index > 1;
        if (index == 0)
        {
            this.addUser();
        }

        multiViewUserManager.ActiveViewIndex = index;
    }

    protected void doOnUserProfileMenuClick(object sender, MenuEventArgs e)
    {
        int index = Int32.Parse(e.Item.Value);
        multiViewUserManager.ActiveViewIndex = index;
    }


    protected void multiViewUserManager_ActiveViewChanged(object sender, EventArgs e)
    {
        userProfileMenu.Visible = this.multiViewUserManager.ActiveViewIndex > 1;
        if (this.multiViewUserManager.ActiveViewIndex == 0)
        {
            setAddUserData();
        }
        else if (this.multiViewUserManager.ActiveViewIndex == 1)
        {
            setListUserData();
        }
        else if (this.multiViewUserManager.ActiveViewIndex == 2)
        {
            setEditUser();
        }
        else if (this.multiViewUserManager.ActiveViewIndex == 4)
        {
            setEditPermissionData();
        }
    }

    private void setListUserData()
    {
        coUserList = UserManagement.GetUserList();
        
        if (ViewState[csFilterMode] != null)
        {
            FilterMode filterMode = (FilterMode)Enum.Parse(typeof(FilterMode), ViewState[csFilterMode].ToString());
            gridListUsers.DataSource = FilterUserList(filterMode);
        }
        else
        {
            gridListUsers.DataSource = coUserList;
        }

        gridListUsers.DataBind();
    }

    private void setAddUserData()
    {
    }

    private void setPermissionData()
    {
        this.cbPermissions.DataSource = UserManagement.GetUserPermissions();
        this.cbPermissions.DataTextField = "Description";
        this.cbPermissions.DataValueField = "Value";
        this.cbPermissions.DataBind();
    }

    private void setEditPermissionData()
    {
        try
        {
            setPermissionData();
            string lsUsername = Convert.ToString(Session["CurrentUser"]);
            User loUser = UserManagement.GetUserByUsername(lsUsername);
            if (loUser.Permission.CompareTo("") != 0)
            {
                cbPermissions.SelectedValue = loUser.Permission;
            }
            this.cbPermissions.Enabled = this.btnUpdatePermission.Enabled =
                !loUser.IsSuperUser;
        }
        catch
        {
            cbPermissions.SelectedValue = null;
        }
    }

    private void setEditUser()
    {
        String lsUsername = Convert.ToString(Session["CurrentUser"]);
        UserProfile loUserProfile = UserProfileManagement.GetUserProfile(lsUsername);
        if (loUserProfile != null)
        {
            lblEditUserName.Text = loUserProfile.Username;
            tbEditUserEmail.Text = loUserProfile.Email;
            if (loUserProfile.Birthday.Equals(DateTime.MinValue) ||
                loUserProfile.Birthday.Equals(DateTime.MaxValue))
            {
                tbBirthDay.Text = "";
            }
            else
            {
                tbBirthDay.Text = loUserProfile.Birthday.ToShortDateString();
            }
            if (loUserProfile.Birthday.Year >= 1900 && loUserProfile.Birthday.Year <= DateTime.Now.Year)
            {
                calBirthday.VisibleDate = loUserProfile.Birthday;
            }
            chkDoNotDisplayAgeInProfile.Checked = loUserProfile.HideBirthday;
            txtAddress.Text = loUserProfile.Address;
            txtAddress2.Text = loUserProfile.Address2;
            txtCity.Text = loUserProfile.City;
            txtState.Text = loUserProfile.State;
            txtZip.Text = loUserProfile.Zip;
            txtCountry.Text = loUserProfile.Country;
            txtSignature.Text = loUserProfile.Signature;
        }
    }

    #region actions

    protected void gridListUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gridListUsers.PageIndex = e.NewPageIndex;
        this.setListUserData();
    }

    public void addUser()
    {
    }

    protected void btnSaveAddUser_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            UserProfile loUser = new UserProfile();
            loUser.Username = txtUsername.Text;
            loUser.Password = txtPassword.Text;
            loUser.Email = txtEmail.Text;
            loUser.Permission = "0";
            UserProfileManagement.SaveUserProfile(loUser, "New");
            this.activateViewListUsers();
        }
    }

    protected void btnCancelAddUser_Click(object sender, EventArgs e)
    {
        this.activateViewListUsers();
    }

    protected void btnSaveEditUserProfile_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            UserProfile loUserProfile = UserProfileManagement.GetUserProfile(lblEditUserName.Text);
            loUserProfile.Username = lblEditUserName.Text;
            loUserProfile.Email = tbEditUserEmail.Text;
            loUserProfile.Birthday = calBirthday.SelectedDate;
            loUserProfile.HideBirthday = chkDoNotDisplayAgeInProfile.Checked;
            loUserProfile.Address = txtAddress.Text;
            loUserProfile.Address2 = txtAddress2.Text;

            loUserProfile.City = txtCity.Text;
            loUserProfile.State = txtState.Text;
            loUserProfile.Zip = txtZip.Text;
            loUserProfile.Country = txtCountry.Text;
            loUserProfile.Signature = txtSignature.Text;

            UserProfileManagement.SaveUserProfile(loUserProfile, "Update");
            setEditUser();
            this.lblEditUserProfileMsg.CssClass = "messageOk";
            this.lblEditUserProfileMsg.Text = "Userprofile updated!";
        }
    }

    protected void btnCancelEditUserProfile_Click(object sender, EventArgs e)
    {
        this.activateViewListUsers();
    }
    #endregion
    #region Validation
    public const string UserNameValidatorError = "Username is a required field";
    public const string EmailemptyValidationError = "Email is a required field";
    public const string PasswordemptyValidationError = "Password is a required field";
    public const string EmailContentValidationError = "Invalid Email Address";

    private bool validate(string pValue, string pRegEx)
    {
        RegexStringValidator validator = new RegexStringValidator(pRegEx);
        try
        {

            validator.Validate(pValue);
        }
        catch
        {
            return false;
        }
        return true;
    }
    protected void cvAddUserName_ServerValidate(object source, ServerValidateEventArgs args)
    {
        Regex regEx = new Regex(@"[_\W]");
        if (string.IsNullOrEmpty(args.Value))
        {
            cvAddUserName.ErrorMessage = UserNameValidatorError;
            args.IsValid = false;
        }

        else if (regEx.IsMatch(args.Value))
        {
            cvAddUserName.ErrorMessage = "Username can only contain alpha-numeric characters!";
            args.IsValid = false;
        }
        else if (!UserManagement.IsUsernameAvailable(args.Value))
        {
            cvAddUserName.ErrorMessage = "A user already exists for the username specified!";
            args.IsValid = false;
        }
    }

    protected void cvAddUserEmail_ServerValidate(object source, ServerValidateEventArgs args)
    {
        CustomValidator validator = source as CustomValidator;
        if (string.IsNullOrEmpty(args.Value))
        {
            validator.ErrorMessage = EmailemptyValidationError;
            args.IsValid = false;
        }
        else if (!validate(args.Value, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
        {
            validator.ErrorMessage = "Invalid Email Address";
            args.IsValid = false;
        }
    }

    protected void cvAdduserVerify_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (txtPassword.Text.Length > 0)
        {
            args.IsValid = txtPassword.Text.Equals(txtVerify.Text);
        }
    }


    protected void cvChangePasswordVerify_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (tbChangePassword.Text.Length > 0)
        {
            args.IsValid = tbChangePassword.Text.Equals(tbChangePasswordVerify.Text);
        }
    }


    #endregion

    private int getTotalIndexFromGrid(GridView pView, int piIndex)
    {
        return (pView.PageSize * pView.PageIndex) + piIndex;
    }

    protected void gridListUsers_RowEditing(object sender, GridViewEditEventArgs e)
    {
        List<User> data = gridListUsers.DataSource as List<User>;
        User loCurrentUser = data[getTotalIndexFromGrid(gridListUsers, e.NewEditIndex)];
        Session["CurrentUser"] = loCurrentUser.Username;
        this.multiViewUserManager.ActiveViewIndex = 2;
    }

    protected void gridListUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        List<User> data = gridListUsers.DataSource as List<User>;
        User head = data[getTotalIndexFromGrid(gridListUsers, e.RowIndex)];
        if (head.IsSuperUser)
        {
            lblListUserMessage.Text = "You can't delete this user!";
            lblListUserMessage.CssClass = "messageError";
        }
        else
        {
            UserProfileManagement.DeleteUserProfile(head.Username);
            this.setListUserData();
        }
    }

    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        this.tbBirthDay.Text = this.calBirthday.SelectedDate.ToShortDateString();
        this.pnlDate.Visible = false;
    }
    protected void Button1_Click1(object sender, EventArgs e)
    {
        this.pnlDate.Visible = !this.pnlDate.Visible;
    }

    protected void gridListUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        addRowSpecifics((GridView)sender, e);
    }

    private void addRowSpecifics(GridView gv, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            User head = e.Row.DataItem as User;
            foreach (DataControlField dcf in gv.Columns)
            {
                CommandField cmf = dcf as CommandField;
                if (cmf != null && (cmf.ShowDeleteButton))
                    if (head.IsSuperUser)
                        e.Row.Cells[gv.Columns.IndexOf(dcf)].Controls.Clear();
                    else
                        e.Row.Cells[gv.Columns.IndexOf(dcf)].Attributes
                        .Add("onclick", "return confirm(\"Are you sure you want to delete this user?\")");
            }
        }
    }

    protected void cbEditUserYear_SelectedIndexChanged(object sender, EventArgs e)
    {
    }

    protected void cbEditUserMonth_SelectedIndexChanged(object sender, EventArgs e)
    {
    }

    protected void btnUpdatePermission_Click(object sender, EventArgs e)
    {
        bool bReturnValue = false;
        string lsUsername = Convert.ToString(Session["CurrentUser"]);
        bReturnValue =
            UserManagement.SaveUserPermission(cbPermissions.SelectedValue,
                                              lsUsername);
        if (bReturnValue)
        {
            this.lblPermissionMsg.CssClass = "messageOk";
            this.lblPermissionMsg.Text = "Permission updated!";
        }
        else
        {
            this.lblPermissionMsg.CssClass = "messageError";
            this.lblPermissionMsg.Text = "Permission update failed!";
        }

    }

    protected void btnChangePassword_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            string lsUsername = Convert.ToString(Session["CurrentUser"]);
            User loUser = UserManagement.GetUserByUsername(lsUsername);
            UserManagement.SaveUserPassword(tbChangePassword.Text, Convert.ToString(loUser.ID));
            this.lblPasswordMessage.CssClass = "messageOk";
            this.lblPasswordMessage.Text = "Password updated!";
        }
    }

    public List<string> ListMonths()
    {
        List<string> loMonths = new List<string>();
        loMonths.Add("");
        foreach (string month in CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames)
        {
            loMonths.Add(month);
        }
        return loMonths;
    }

    public List<string> ListYears()
    {
        List<string> lsYears = new List<string>();
        lsYears.Add("");
        for (int liCurrentYear = DateTime.Now.Year; liCurrentYear > 1900; liCurrentYear--)
        {
            lsYears.Add(Convert.ToString(lsYears));
        }
        return lsYears;
    }

    public string GetMonthAsString(int pMonth)
    {
        int liIndex = pMonth - 1;
        if (liIndex >= 0 && liIndex < CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames.Length)
            return CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames[liIndex];
        return "";
    }
    protected void FilterByNameButton_Click(object sender, EventArgs e)
    {
        gridListUsers.PageIndex = 0;
        gridListUsers.DataSource = FilterUserList(FilterMode.ByName);
        gridListUsers.DataBind();
        ViewState[csFilterMode] = FilterMode.ByName.ToString();
    }
    protected void FilterByEmailButton_Click(object sender, EventArgs e)
    {
        gridListUsers.PageIndex = 0;
        gridListUsers.DataSource = FilterUserList(FilterMode.ByEmail);
        gridListUsers.DataBind();
        ViewState[csFilterMode] = FilterMode.ByEmail.ToString();
    }
    protected void ShowAllUsersButton_Click(object sender, EventArgs e)
    {
        gridListUsers.PageIndex = 0;
        gridListUsers.DataSource = coUserList;
        gridListUsers.DataBind();
        ViewState[csFilterMode] = null;
    }

    private List<User> FilterUserList(FilterMode filterMode)
    {
        List<User> loUserList = null;

        switch (filterMode)
        {
            case FilterMode.ByName:
                loUserList = coUserList.FindAll(delegate(User user)
                {
                    return user.Username.ToUpperInvariant().
                        Contains(filterTextBox.Text.ToUpperInvariant());
                });
                break;
            case FilterMode.ByEmail:
                loUserList = coUserList.FindAll(delegate(User user)
                {
                    return user.Email.ToUpperInvariant().
                        Contains(filterTextBox.Text.ToUpperInvariant());
                });
                break;
            default:
                break;
        }

        return loUserList;
    }
}
