using System;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web.Configuration;
using System.Web.UI;
using System.Xml;
public partial class System_Settings_SystemSetting_MailConfiguration : Base.BasePage
{
    #region VariableDeclaration
    ResourceManager rm;
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    cls_Common objcommon = new cls_Common();
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        if (!Page.IsPostBack)
        {
            base.CheckPages(0);
            txtMailId.Focus();
        }
        //get the culture info to set the language
        string source_Language;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        LoadStrings(ci);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_EnterAdminEmailId", ci) + "','" + rm.GetString("Alert_EnterIPAddressHostName", ci) + "','" + rm.GetString("Alert_EnterPortNumber", ci) + "','" + rm.GetString("Alert_ConfirmSave", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        //Call to a function to implement the UserRights
        UserRights();
        if (!IsPostBack)
        {
            LoadMailConfiguration();
            objcommon.menu("Configuration", "106");
        }
    }
    #endregion
    #region ButtonEvents
    protected void btn_Add_Click(object sender, EventArgs e)
    {
        if (rbtnAuthenticationYes.Checked == true)
        {
            if (txtUserName.Text.Trim() == string.Empty)
            {
                //Commented below lines because this server side enabled and disabled will not worked once its enabled or disable using javascript : by MAnjula.P on 19-Mar-2014
                //Added this javascript fun : AuthenticateUserEnableDisable(1); calling for enabling txtUserName and txtPassword
                ScriptManager.RegisterStartupScript(this.Page, GetType(), "Javascript", "javascript:AuthenticateUserEnableDisable(1); ", true);
                base.Message(rm.GetString("Alert_EnterUserName", ci));
                return;
            }
            if (txtPassword.Text.Trim() == string.Empty)
            {
                //Commented below lines because this server side enabled and disabled will not worked once its enabled or disable using javascript : by MAnjula.P on 19-Mar-2014
                //Added this javascript fun : AuthenticateUserEnableDisable(1); calling for enabling txtUserName and txtPassword
                ScriptManager.RegisterStartupScript(this.Page, GetType(), "Javascript", "javascript:AuthenticateUserEnableDisable(1); ", true);
                base.Message(rm.GetString("Alert_EnterPassword", ci));
                return;
            }
        }
        try
        {
            //Overwrite Admin mail id 
            OverwriteApplicationConnectionString(txtMailId.Text, "FromId");
            //Overwrite IP Address / Host Name
            OverwriteApplicationConnectionString(txtIPAddress.Text, "SMTPClientHost");
        }
        catch (Exception ex)
        {
            throw ex;
        }
        //Added by Manikandan.R
        //on 22-10-2013 for email scheduler.
        int sslEnabled = 0;
        if (rbtnSSLYes.Checked == true)
        {
            sslEnabled = 1;
        }
        int authenticationEnabled = 0;
        if (rbtnSSLYes.Checked == true)
        {
            authenticationEnabled = 1;
        }
        string password = string.Empty;
        if (txtPassword.Text != string.Empty)
        {
            password = Cryptographys.Cryptography.Encrypt(txtPassword.Text.Trim(), "TimecheckPhaseI");
        }
        ShiftExchange obj = new ShiftExchange();
        obj.InsertMailConfiguration(txtMailId.Text, txtIPAddress.Text, txtSMTPPort.Text, sslEnabled, authenticationEnabled, txtUserName.Text, password, 1);
        base.MessageWithRedirect(rm.GetString("Alert_MailConfigurationSavedSuccessfully", ci), "../Index.aspx");
    }
    #endregion
    #region UserDefinedFunctions
    public void OverwriteApplicationConnectionString(string ConnStr, string strValue)
    {
        XmlDocument doc = new XmlDocument();
        string WebConfigFilename = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath).FilePath;
        doc.Load(WebConfigFilename);
        XmlNodeList oList = doc.SelectNodes("configuration/location/appSettings/add");
        for (int i = 0; i < oList.Count; i++)
        {
            XmlAttribute oKey = oList[i].Attributes["key"];
            XmlAttribute oValue = oList[i].Attributes["value"];
            if (oKey.Value == "FromId")
            {
                oValue.Value = txtMailId.Text;
            }
            if (oKey.Value == "SMTPClientHost")
            {
                oValue.Value = txtIPAddress.Text;
            }
            if (oKey.Value == "SMTPPort")
            {
                oValue.Value = txtSMTPPort.Text;
            }
            if (oKey.Value == "SSLEnable")
            {
                int intChecked = 0;
                if (rbtnSSLYes.Checked == true)
                {
                    intChecked = 1;
                }
                oValue.Value = intChecked.ToString();
            }
            if (oKey.Value == "MailAuthentication")
            {
                int intMailAuthChecked = 0;
                if (rbtnAuthenticationYes.Checked == true)
                {
                    intMailAuthChecked = 1;
                }
                oValue.Value = intMailAuthChecked.ToString();
            }
            if (oKey.Value == "MailAuthenticateUser")
            {
                if (rbtnAuthenticationNo.Checked == true)
                {
                    oValue.Value = string.Empty;
                }
                else
                {
                    oValue.Value = txtUserName.Text;
                }
            }
            if (oKey.Value == "MailAuthenticatePassword")
            {
                if (rbtnAuthenticationNo.Checked == true)
                {
                    oValue.Value = string.Empty;
                }
                else
                {
                    oValue.Value = Cryptographys.Cryptography.Encrypt(txtPassword.Text.Trim(), "TimecheckPhaseI");
                }
            }
        }
        //Un comment the following while creating setup
        doc.Save(WebConfigFilename);
    }
    //Getting Information from resource file and display it in label
    private void LoadMailConfiguration()
    {
        XmlDocument doc = new XmlDocument();
        string WebConfigFilename = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath).FilePath;
        doc.Load(WebConfigFilename);
        XmlNodeList oList = doc.SelectNodes("configuration/location/appSettings/add");
        for (int i = 0; i < oList.Count; i++)
        {
            XmlAttribute oKey = oList[i].Attributes["key"];
            XmlAttribute oValue = oList[i].Attributes["value"];
            if (oKey.Value == "FromId")
            {
                txtMailId.Text = oValue.Value.ToString();
            }
            if (oKey.Value == "SMTPClientHost")
            {
                txtIPAddress.Text = oValue.Value.ToString();
            }
            if (oKey.Value == "SMTPPort")
            {
                txtSMTPPort.Text = oValue.Value.ToString();
            }
            if (oKey.Value == "SSLEnable")
            {
                if (oValue.Value.ToString() == "0")
                {
                    rbtnSSLNo.Checked = true;
                }
                else
                {
                    rbtnSSLYes.Checked = true;
                }
            }
            if (oKey.Value == "MailAuthentication")
            {
                if (oValue.Value.ToString() == "0")
                {
                    rbtnAuthenticationNo.Checked = true;
                    txtUserName.BackColor = System.Drawing.ColorTranslator.FromHtml("#d3dbe7");
                    txtPassword.BackColor = System.Drawing.ColorTranslator.FromHtml("#d3dbe7");
                    txtUserName.Enabled = false;
                }
                else
                {
                    rbtnAuthenticationYes.Checked = true;
                    txtUserName.Enabled = true;
                }
            }
            if (oKey.Value == "MailAuthenticateUser")
            {
                txtUserName.Text = oValue.Value.ToString();
            }
        }
    }
    private void LoadStrings(CultureInfo ci)
    {
        btn_Add.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        lbl_Header.Text = rm.GetString("System_MailConfiguration", ci);
        lblUserName.Text = rm.GetString("EmployeeMaster_UserName", ci);
        lblPassword.Text = rm.GetString("Caption_Password", ci);
        lblMailId.Text = rm.GetString("Admin_Mail_Id", ci);
        lblServerIP.Text = rm.GetString("ServerIP_HostName", ci);
        lblSMTPPort.Text = rm.GetString("SMTP_Port", ci);
        lblSSLEnable.Text = rm.GetString("SSL_Enable", ci);
        lblAuthentication.Text = rm.GetString("Authentication", ci);
        rbtnAuthenticationNo.Text = rm.GetString("ShiftSetting_No", ci);
        rbtnAuthenticationYes.Text = rm.GetString("ShiftSetting_Yes", ci);
        rbtnSSLNo.Text = rm.GetString("ShiftSetting_No", ci);
        rbtnSSLYes.Text = rm.GetString("ShiftSetting_Yes", ci);
        RegVtxtMailId.ErrorMessage = rm.GetString("Alert_EnterValidEmailId", ci);
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(106, Convert.ToInt32(Session["userGroup_Id"]), "addPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("SystemLandingPage.aspx");
        }
    }
    #endregion
}