using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLayer;
using DTO;
using Helper;

namespace NikaiDSR.Controls
{
    public partial class AddEditUser : PageBase
    {
        #region declarartion
        CommonManager CM = new CommonManager();
        UserManager UM = new UserManager();
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Page.Title = "NIKAI - ADD/EDIT USERS";
                FillLocationComboBox();
                FillRoleComboBox();
                FillLanguageCombobox();

                if (!string.IsNullOrEmpty(Request.QueryString["UserId"]))
                {
                    FillData();
                }
            }
        }

        void FillLocationComboBox()
        {
            IList<LocationDTO> LocationList = CM.GetLocation(null, null, null);
            Helper.Validation.FillTelerikDropdown(cmbLocation, LocationList, "Location_Name", "Location_Id", "Select Location", "0");
        }

        void FillRoleComboBox()
        {
            IList<RoleDTO> RoleList = CM.GetRole(null, null);
            Helper.Validation.FillTelerikDropdown(cmbRole, RoleList, "Role_Name", "Role_Id", "Select Role", "0");
        }

        void FillLanguageCombobox()
        {
            IList<ParameterDTO> Languages = CM.GetLanguages();
            Helper.Validation.FillTelerikDropdown(cmbLanguage, Languages, "Description", "ParameterDetId", "Select", "0");
        }

        void FillData()
        {
            UserDTO User = UM.GetUser(Convert.ToInt32(Request.QueryString["UserId"]), null, null);
            txtName.Text = User.Name;
            txtEmail.Text = User.Email;
            cmbRole.SelectedValue = User.Role_Id.ToString();
            cmbLocation.SelectedValue = User.Location_Id.ToString();
            rbtStatus.SelectedValue = (User.Status == true) ? "1" : "2";
            txtEmployeeCode.Text = User.Employee_Code;
            cmbLanguage.SelectedValue = User.Language_Id.ToString();
            BindCheckBox();

            IList<ManagerExecutivesDTO> LinkedExecutives = CM.GetLinkedExecutives(Convert.ToInt32(Request.QueryString["UserId"]));

            foreach (ListItem item in ChkManagers.Items)
            {
                if (LinkedExecutives.Select(c => c.Site_User_Id).Contains(Convert.ToInt32(item.Value)))
                    item.Selected = true;
            }
        }

        protected void cmbRole_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            BindCheckBox();
        }

        protected void cmbLocation_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            BindCheckBox();
        }

        void BindCheckBox()
        {
            // not sales executive
            if (Validation.ComboBoxValidate(cmbRole) && cmbRole.SelectedValue != "5")
            {
                IList<ReporteesForUserCreationDTO> UserList = UM.GetReporteesForUserCreation(Convert.ToInt32(cmbRole.SelectedValue), Convert.ToInt32(cmbLocation.SelectedValue));

                ChkManagers.DataTextField = "Name";
                ChkManagers.DataValueField = "Site_User_Id";
                ChkManagers.DataSource = UserList.Where(c => c.Site_User_Id != UserID);
                ChkManagers.DataBind();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string Error = "";
            if (!Validate(ref Error))
                ShowErrorMessage(Error, errMsg, Common.ERROR_MESSAGE_TYPE.ERROR);
            else
            {
                UserDTO user = new UserDTO();
                if (!string.IsNullOrEmpty(Request.QueryString["UserId"]))
                {
                    user.Site_User_Id = Convert.ToInt32(Request.QueryString["UserId"]);
                    user.Password = UM.GetUser(user.Site_User_Id, "", "").Password;
                }
                else
                {
                    user.Password = Common.GenerateRandomPassword(8);
                }

                user.Employee_Code = txtEmployeeCode.Text;
                user.Name = txtName.Text;
                user.Email = txtEmail.Text;
                user.Role_Id = Convert.ToInt32(cmbRole.SelectedValue);
                user.Location_Id = Convert.ToInt32(cmbLocation.SelectedValue);
                user.Language_Id = Convert.ToInt32(cmbLanguage.SelectedValue);
                user.Status = (rbtStatus.SelectedValue == "1") ? true : false;

                IList<int> LinkedExecutiveIds = new List<int>();
                foreach (ListItem item in ChkManagers.Items)
                {
                    if (item.Selected == true)
                        LinkedExecutiveIds.Add(Convert.ToInt32(item.Value));
                }

                user.LinkedExecutiveIds = LinkedExecutiveIds;
                UM.InsertUpdateUser(user);

                if (user.Status == true)
                {
                    String EmailBody = "Dear " + user.Name + ",<br/><br/>Your account has been created successfully to access the online Nikai Sales Reporting website.<br/>"
                                       +"Welcome !!!<br/><br/> Your login details are : <b><br/>Site URL: <><br/>User name is: " + user.Email + "<br/>Password is: " + user.Password 
                                       + "</b><br/><br/> <b>To Note :</b> The Password provided is temporary. Please change on first Login.<br/><br/>Best Regards,<br/>Nikai Admin";

                    Helper.Common.SendEmail(user.Email, "Nikai - NEW User Created", EmailBody);
                }

                RadAjaxManager2.ResponseScripts.Add(string.Format("RefreshParentPage();", DateTime.Now.ToLongTimeString()));
            }
        }

        bool Validate(ref string Error)
        {
            bool validateFlag = true;

            bool FlagCheckboxSelected = false;
            foreach (ListItem item in ChkManagers.Items)
            {
                if (item.Selected == true)
                {
                    FlagCheckboxSelected = true;
                    break;
                }
            }

            if (!(Validation.TextBoxValidate(txtName)
                && Validation.TextBoxValidate(txtEmail)
                && Validation.ComboBoxValidate(cmbRole)
                && Validation.ComboBoxValidate(cmbLocation)
                && Validation.ComboBoxValidate(cmbLanguage)))
            {
                Error = "Fill all mandatory fields.";
                validateFlag = false;
            }
            else if (ChkManagers.Items.Count > 0 && FlagCheckboxSelected == false)
            {
                Error = "Select Repotees for Manager";
                validateFlag = false;
            }
            else if (string.IsNullOrEmpty(Request.QueryString["UserId"]))
            {
                if (UM.IsEmailDuplicate(txtEmail.Text))
                {
                    Error = "Email is already used.";
                    validateFlag = false;
                }
            }

            return validateFlag;
        }
    }
}