// Personal Webpage Engine
// Copyright(c) 2008 Mihail Kochanov
// You can contact me at StilgarAD@yahoo.com
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//------------------------------------------------------------------------------
//
// Personal Web Page Engine
//
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Private
{
    public partial class EditProfile : System.Web.UI.Page
    {

        #region Properties

        string username;
        MembershipUser paramUser; //user to view profile
        MembershipUser currentUser; //currently logged user
        bool isCurrentUserAdmin;
        string[] paramUserRoles;

        #endregion

        #region PageEvents

        protected void Page_PreInit(object sender, EventArgs e)
        {
            username = Request.QueryString[Constants.QueryString.Username];

            if (String.IsNullOrEmpty(username))
            {
                Response.Redirect("~/Main.aspx");
            }

            currentUser = Membership.GetUser();
            paramUser = Membership.GetUser(username);

            if (paramUser == null)
            {
                Session[Constants.Session.ErrorMessage] = Constants.Error.InvalidUser;
                Server.Transfer("~/Error.aspx");
            }

            isCurrentUserAdmin = Roles.IsUserInRole(Constants.Roles.Admin);
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            if (isCurrentUserAdmin && currentUser.UserName != username)
            {
                pnlAdmin.Visible = true;

                paramUserRoles = Roles.GetRolesForUser(username);

                foreach (string role in Roles.GetAllRoles())
                {
                    pnlRoles.Controls.Add(new CheckBox { Text = role, Checked = paramUserRoles.Contains(role) });
                    pnlRoles.Controls.Add(new Literal { Text = "<br />" });
                }
            }

            if (currentUser.UserName == username || isCurrentUserAdmin)
            {
                pnlMain.Visible = true;
                pnlDenied.Visible = false;

                lbUsername.Text = username;
                txtNewEmail.Text = paramUser.Email;

                txtNewSecretQuestion.Text = paramUser.PasswordQuestion;

                revNewPassword.ValidationExpression = ".{" + Membership.Provider.MinRequiredPasswordLength + ",}";
                revNewPassword.ErrorMessage = "Minimum password length is " + Membership.Provider.MinRequiredPasswordLength + " characters";

                revNewPasswordConfirm.ValidationExpression = revNewPassword.ValidationExpression;
                revNewPasswordConfirm.ErrorMessage = revNewPassword.ErrorMessage;
            }
            else
            {
                pnlMain.Visible = false;
                pnlDenied.Visible = true;
            }

            this.Title = "Edit profile for user " + username;
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            //set the values that has been changed by activate/deactivate buttons
            if (isCurrentUserAdmin && currentUser.UserName != username)
            {
                lbIsActive.Text = paramUser.IsApproved ? "active" : "deactivated";

                if (paramUser.IsApproved)
                {
                    btnActivateUser.Visible = false;
                    btnDeactivateUser.Visible = true;
                }
                else
                {
                    btnActivateUser.Visible = true;
                    btnDeactivateUser.Visible = false;
                }
            }
        }

        #endregion

        #region ControlEvents

        protected void btnSave_Click(object sender, EventArgs e)
        {
            bool changePassword = false;
            bool changeQuestionAndAnswer = false;
            bool changeEmail = false;

            bool passwordVerified = false;

            lbError.Visible = true;

            //check what has been changed
            #region CheckChanges

            if (txtNewPassword.Text != "" || txtNewPasswordConfirm.Text != "")
            {
                if (txtNewPassword.Text == txtNewPasswordConfirm.Text)
                {
                    if (txtCurrentPassword.Text != "")
                    {
                        changePassword = true;
                    }
                    else
                    {
                        lbError.Text = "Current password required for password change.";
                        return;
                    }
                }
                else
                {
                    lbError.Text = "Password does not match with confirm password.";
                    return;
                }
            }

            if (txtNewSecretAnswer.Text.Trim() != "")
            {
                if (txtNewSecretQuestion.Text.Trim() != "")
                {
                    changeQuestionAndAnswer = true;
                }
                else
                {
                    lbError.Text = "Question required for answer change.";
                    return;
                }
            }

            if (txtNewEmail.Text.Trim() != paramUser.Email)
            {
                changeEmail = true;
            }

            #endregion



            //change what has to be changed
            #region SubmitChanges

            if (changePassword)
            {
                if (txtCurrentPassword.Text == "")
                {
                    lbError.Text = "Password required for password change.";
                    return;
                }

                if (paramUser.ChangePassword(txtCurrentPassword.Text, txtNewPassword.Text))
                {
                    lbError.Text = "Password changed successfully. ";
                    txtCurrentPassword.Text = txtNewPassword.Text;
                    passwordVerified = true;
                }
                else
                {
                    if (!Membership.ValidateUser(paramUser.UserName, txtCurrentPassword.Text))
                    {
                        lbError.Text = "Incorrect current password.";
                        return;

                    }
                    else
                    {
                        lbError.Text = "Error while trying to change password.";
                        return;
                    }
                }
            }

            if (changeQuestionAndAnswer)
            {
                if (txtCurrentPassword.Text == "")
                {
                    lbError.Text = "Password required for secret question change.";
                    return;
                }

                if (paramUser.ChangePasswordQuestionAndAnswer(txtCurrentPassword.Text, txtNewSecretQuestion.Text, txtNewSecretAnswer.Text))
                {
                    lbError.Text += "Secret question changed successfully. ";
                    passwordVerified = true;
                }
                else
                {
                    if (!Membership.ValidateUser(paramUser.UserName, txtCurrentPassword.Text))
                    {
                        lbError.Text = "Incorrect current password.";
                        return;
                    }
                    else
                    {
                        lbError.Text += "Error while trying to change secret question and answer.";
                        return;
                    }
                }
            }

            if (changeEmail)
            {
                if (!isCurrentUserAdmin && txtCurrentPassword.Text == "")
                {
                    lbError.Text = "Password required for e-mail change.";
                    return;
                }

                if (passwordVerified || isCurrentUserAdmin || Membership.ValidateUser(paramUser.UserName, txtCurrentPassword.Text))
                {
                    paramUser.Email = txtNewEmail.Text.Trim();
                    lbError.Text += "E-mail changed successfully. ";
                }
                else
                {
                    lbError.Text = "Incorrect current password.";
                    return;
                }
            }

            //update user if anything that requires update has been changed
            if (changeEmail)
            {
                Membership.UpdateUser(paramUser);
            }

            #endregion


            if (lbError.Text == "")
            {
                lbError.Text = "Profile information saved";
            }


            Cache.Remove(Constants.Cache.Users);
        }

        protected void btnDeleteUser_Click(object sender, EventArgs e)
        {
            Membership.DeleteUser(username, true);

            Cache.Remove(Constants.Cache.Users);

            Response.Redirect("~/Admin/UserManagement.aspx");
        }

        protected void btnDeactivateUser_Click(object sender, EventArgs e)
        {
            paramUser.IsApproved = false;
            Membership.UpdateUser(paramUser);

            Cache.Remove(Constants.Cache.Users);
        }

        protected void btnActivateUser_Click(object sender, EventArgs e)
        {
            paramUser.IsApproved = true;
            Membership.UpdateUser(paramUser);

            Cache.Remove(Constants.Cache.Users);
        }

        protected void btnSaveRoles_Click(object sender, EventArgs e)
        {
            List<string> rolesToAdd = new List<string>();
            List<string> rolesToRemove = new List<string>();

            foreach (Control c in pnlRoles.Controls)
            {
                CheckBox cb = c as CheckBox;
                if (cb != null)
                {
                    if (cb.Checked && !paramUserRoles.Contains(cb.Text))
                    {
                        rolesToAdd.Add(cb.Text);
                    }
                    else if (paramUserRoles.Contains(cb.Text))
                    {
                        rolesToRemove.Add(cb.Text);
                    }
                }
            }

            if (rolesToAdd.Count > 0)
            {
                Roles.AddUserToRoles(username, rolesToAdd.ToArray());
            }
            if (rolesToRemove.Count > 0)
            {
                Roles.RemoveUserFromRoles(username, rolesToRemove.ToArray());
            }

            lbUserStatus.Visible = true;
            lbUserStatus.Text = "Roles saved successfully";
        }

        #endregion

    }
}