using System;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class System_Settings_ExportData_FieldName : System.Web.UI.Page
{
    #region VariableDeclaration
    MonthClosureEventData objMonthClosureEventData = new MonthClosureEventData();
    ExportData objExportEventData = new ExportData();
    DataSet dsFieldNames = new DataSet();
    string Optiontype = string.Empty;
    string DailyOrSummarizedData = string.Empty;
    ResourceManager rm;
    CultureInfo ci;
    DataSet dsFieldOption = new DataSet();
    #endregion
    #region PageLoad
    /// <summary>
    /// Page load event
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Session_ActiveLanguage"] == null)
        {
            string str = "<script language=\"javascript\">";
            //str = str + "opener.focus();";
            str = str + "top.location.href = top.location + '?fl=1&sid=" + Session.SessionID + "';";
            str = str + "parent.$('#myModal').modal('hide');";
            str = str + "</script>";
            Response.Write(str);
        }
        // Get the culture info to set the language
        string sourceLanguage = string.Empty;
        sourceLanguage = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(sourceLanguage, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        LoadStrings(ci);
        btnCancel.OnClientClick = "if(confirm('" + rm.GetString("Alert_SureToExit") + "')) parent.$('#myModal').modal('hide');";
        Optiontype = Request.QueryString["Option"].ToString();
        DailyOrSummarizedData = Request.QueryString["DailyOrSummarizedData"].ToString();
        dsFieldOption.Tables.Add();
        dsFieldOption.Tables[0].Columns.Add("Fieldtype");
        dsFieldOption.Tables[0].Rows.Add("Normal");
        dsFieldOption.Tables[0].Rows.Add("Date");
        dsFieldOption.Tables[0].Rows.Add("Time");
        dsFieldOption.Tables[0].Rows.Add("Date&Time");
        loadcss();
        if (!IsPostBack)
        {
            CompanyBinding();
            if (Optiontype == "All")
            {
                FillFieldNames_All();
            }
            else if (Optiontype == "OT")
            {
                FillFieldNames_OT();
            }
            else if (Optiontype == "Attendance")
            {
                FillFieldNames_Attendance();
            }
        }
       
    }
    #endregion
    #region UserDefinedFunctions
    /// <summary>
    /// Getting Information from resource file and display it in label
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        lblCompany.Text = rm.GetString("EntranceMaster_Company", ci);
        lbl_Header.Text = rm.GetString("Caption_ExportDataCustomFields", ci);
        lblDateFormat.Text = rm.GetString("DateandTimeFormat_DateFormat", ci);
        lblTimeFormat.Text = rm.GetString("DateandTimeFormat_TimeFormat", ci);
        lblDateTimeFormat.Text = rm.GetString("Menu_SystemSettings_DateandTimeFormat", ci);
        lblXMLTag.Text = rm.GetString("Caption_XMLTag", ci);
        lblRootName.Text = rm.GetString("Caption_RootName", ci);
        lblFirstChildName.Text = rm.GetString("Caption_FirstChildName", ci);
        gvFieldData.Columns[0].HeaderText = rm.GetString("Caption_FieldName", ci);
        gvFieldData.Columns[1].HeaderText = rm.GetString("Caption_UserDefinedFieldName", ci);
        gvFieldData.Columns[3].HeaderText = rm.GetString("Caption_FieldType", ci);
        btnSave.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btnCancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Cancel", ci);
    }

    private void loadcss()
    {
        CultureInfo ci;
        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;
        //if Standard Demo
        htmlExportField.Attributes.Add("dir", rm.GetString("Direction", ci));
        if (source_Language == "Resources.Resource_AR")
        {
            stylebootstrap.Href = "../bootstrap/css/bootstrap-rtl.min.css";
            stylefontawesome.Href = "../bootstrap/font-awesome/css/font-awesome-rtl.css";
            styleAdminLTE.Href = "../dist/css/AdminLTE.min-rtl.css";
            stylecustom.Href = "../dist/css/custom-rtl.css";
            stylefonts.Href = "../dist/css/fonts.css";
            styleselect2.Href = "../plugins/select2/select2.min-rtl.css";
        }
        else
        {
            stylebootstrap.Href = "../bootstrap/css/bootstrap.min.css";
            stylefontawesome.Href = "../bootstrap/font-awesome/css/font-awesome.css";
            styleAdminLTE.Href = "../dist/css/AdminLTE.min.css";
            stylecustom.Href = "../dist/css/custom.css";
            stylefonts.Href = "../dist/css/fonts.css";
            styleselect2.Href = "../plugins/select2/select2.min.css";
        }
    }

    /// <summary>
    /// binds the companies in the drop down
    /// </summary>
    private void CompanyBinding()
    {
        ShiftEvenData objShift = new ShiftEvenData();
        string gstrUserGroupName = string.Empty;
        DataSet dsCompany = new DataSet();
        gstrUserGroupName = Convert.ToString(Session["UserGroupName"]);
        dsCompany = objShift.SelectCompany(gstrUserGroupName, Convert.ToString(Session["LevelRights"]), 0);
        if (dsCompany != null)
        {
            if (dsCompany.Tables[0].Rows.Count > 0)
            {
                ddlCompany.DataSource = dsCompany;
                ddlCompany.DataTextField = "CompanyName";
                ddlCompany.DataValueField = "CompanyId";
                ddlCompany.DataBind();
            }
            foreach (ListItem item in ddlCompany.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
    }
    /// <summary>
    /// Generate dynamic controls for all fields.For All option.
    /// </summary>
    /// 
    private void FillFieldNames_All()
    {
        //To fill custom formats.
        FillCustomFields("All");
        //To fill field names.
        dsFieldNames = objExportEventData.GetCustomFieldNamesForExportData("All", DailyOrSummarizedData, Convert.ToInt16(ddlCompany.SelectedValue));
        if (dsFieldNames.Tables[0].Rows.Count == 0)
        {
            dsFieldNames = objMonthClosureEventData.GetPayrollFieldNames(DailyOrSummarizedData, Convert.ToInt16(ddlCompany.SelectedValue));
        }
        if (dsFieldNames != null)
        {
            if (dsFieldNames.Tables[0].Rows.Count > 0)
            {
                gvFieldData.DataSource = dsFieldNames.Tables[0];
                gvFieldData.DataBind();
            }
        }
        //TO fill field type in the drop down.
        FillFieldType();
    }
    /// <summary>
    /// Generate dynamic controls for all fields.For OT option.
    /// </summary>
    private void FillFieldNames_OT()
    {
        //To fill custom formats.
        FillCustomFields("OT");
        //To fill field names.
        dsFieldNames = objExportEventData.GetCustomFieldNamesForExportData("OT", DailyOrSummarizedData, Convert.ToInt16(ddlCompany.SelectedValue));
        if (dsFieldNames.Tables[0].Rows.Count == 0 || dsFieldNames.Tables.Count == 0)
        {
            if (dsFieldNames.Tables.Count != 0)
            {
                dsFieldNames.Tables.RemoveAt(0);
            }
            dsFieldNames.Tables.Add();
            dsFieldNames.Tables[0].Columns.Add("FieldName");
            dsFieldNames.Tables[0].Columns.Add("UserDefinedFieldName");
            dsFieldNames.Tables[0].Columns.Add("FieldType");
            dsFieldNames.Tables[0].Rows.Add("employee_code");
            dsFieldNames.Tables[0].Rows.Add("pay_year");
            dsFieldNames.Tables[0].Rows.Add("pay_month");
            dsFieldNames.Tables[0].Rows.Add("NormOTMins");
            dsFieldNames.Tables[0].Rows.Add("WeekOffOTMins");
            dsFieldNames.Tables[0].Rows.Add("HolidayOTMins");
        }
        if (dsFieldNames != null)
        {
            if (dsFieldNames.Tables[0].Rows.Count > 0)
            {
                gvFieldData.DataSource = dsFieldNames.Tables[0];
                gvFieldData.DataBind();
            }
        }
        //TO fill field type in the drop down.
        FillFieldType();
    }
    /// <summary>
    /// Generate dynamic controls for all fields.For Attendance option.
    /// </summary>
    private void FillFieldNames_Attendance()
    {
        //To fill custom formats.
        FillCustomFields("Attendance");
        //To fill field names.
        dsFieldNames = objExportEventData.GetCustomFieldNamesForExportData("Attendance", DailyOrSummarizedData, Convert.ToInt16(ddlCompany.SelectedValue));
        if (dsFieldNames.Tables[0].Rows.Count == 0 || dsFieldNames.Tables.Count == 0)
        {
            dsFieldNames.Tables.RemoveAt(0);
            dsFieldNames.Tables.Add();
            dsFieldNames.Tables[0].Columns.Add("FieldName");
            dsFieldNames.Tables[0].Columns.Add("UserDefinedFieldName");
            dsFieldNames.Tables[0].Columns.Add("FieldType");
            dsFieldNames.Tables[0].Rows.Add("employee_code");
            dsFieldNames.Tables[0].Rows.Add("pay_month");
            dsFieldNames.Tables[0].Rows.Add("pay_year");
            dsFieldNames.Tables[0].Rows.Add("PresentDays");
            dsFieldNames.Tables[0].Rows.Add("AbsentDays");
            dsFieldNames.Tables[0].Rows.Add("LeaveDays");
        }
        if (dsFieldNames != null)
        {
            if (dsFieldNames.Tables[0].Rows.Count > 0)
            {
                gvFieldData.DataSource = dsFieldNames.Tables[0];
                gvFieldData.DataBind();
            }
        }
        //TO fill field type in the drop down.
        FillFieldType();
    }
    /// <summary>
    /// Fills the drop down with the field type.
    /// </summary>
    private void FillFieldType()
    {
        foreach (GridViewRow gvRow in gvFieldData.Rows)
        {
            DropDownList ddlFieldType = (DropDownList)gvFieldData.Rows[gvRow.RowIndex].FindControl("ddlFieldType");
            ddlFieldType.Items.Clear();
            ddlFieldType.DataSource = dsFieldOption.Tables[0];
            ddlFieldType.DataTextField = "FieldType";
            ddlFieldType.DataValueField = "FieldType";
            ddlFieldType.DataBind();
            foreach (ListItem item in ddlFieldType.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
            Label lblFieldtype = (Label)gvFieldData.Rows[gvRow.RowIndex].FindControl("lblFieldType");
            if (lblFieldtype.Text != string.Empty)
            {
                ddlFieldType.SelectedValue = lblFieldtype.Text;
            }
            else
            {
                ddlFieldType.SelectedValue = "Normal";
            }
        }
    }
    /// <summary>
    /// To fill custom formats.
    /// </summary>
    /// <param name="Option"></param>
    private void FillCustomFields(string Option)
    {
        DataSet dsCustomFormat = new DataSet();
        dsCustomFormat = objExportEventData.GetCustomFormatsForExportData(Option, DailyOrSummarizedData, Convert.ToInt16(ddlCompany.SelectedValue));
        if (dsCustomFormat.Tables.Count > 0)
        {
            if (dsCustomFormat.Tables[0].Rows.Count > 0)
            {
                ddlDateFormat.SelectedValue = dsCustomFormat.Tables[0].Rows[0]["DateFormat"].ToString();
                ddlTimeFormat.SelectedValue = dsCustomFormat.Tables[0].Rows[0]["TimeFormat"].ToString();
                ddlDateTimeFormat.SelectedValue = dsCustomFormat.Tables[0].Rows[0]["DateTimeFormat"].ToString();
                txtRootName.Text = dsCustomFormat.Tables[0].Rows[0]["XML_RootTag"].ToString();
                txtFirstChildName.Text = dsCustomFormat.Tables[0].Rows[0]["XML_FirstChildTag"].ToString();
            }
        }
    }
    #endregion
    #region ButtonEvents
    /// <summary>
    /// To save the custom datas into the DB.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        DataTable dtCustomFieldData = new DataTable();
        dtCustomFieldData.Columns.Add("OptionType");
        dtCustomFieldData.Columns.Add("FieldName");
        dtCustomFieldData.Columns.Add("UserDefinedFieldName");
        dtCustomFieldData.Columns.Add("FieldType");
        dtCustomFieldData.Columns.Add("DataType");
        dtCustomFieldData.Columns.Add("CompanyID");
        DataRow drFielData;
        foreach (GridViewRow gvRow in gvFieldData.Rows)
        {
            drFielData = dtCustomFieldData.NewRow();
            drFielData["OptionType"] = Optiontype;
            Label lblFiledName = (Label)gvRow.FindControl("lblFieldName");
            drFielData["FieldName"] = lblFiledName.Text;
            TextBox txtUserDefinedFieldName = (TextBox)gvRow.FindControl("txtUserDEfinedField");
            drFielData["UserDefinedFieldName"] = txtUserDefinedFieldName.Text;
            DropDownList ddlFieldType = (DropDownList)gvRow.FindControl("ddlFieldType");
            drFielData["FieldType"] = ddlFieldType.SelectedValue;
            drFielData["DataType"] = DailyOrSummarizedData;
            drFielData["CompanyID"] = Convert.ToInt16(ddlCompany.SelectedValue);
            dtCustomFieldData.Rows.Add(drFielData);
        }
        string strScript = string.Empty;
        bool IsDuplicateExists = false;
        string DuplicateFieldName = string.Empty;
        //Copies the custom field names into to temporary table to check whether duplicate field name exists.
        DataTable dtCustomFieldData_Temp = new DataTable();
        dtCustomFieldData_Temp = dtCustomFieldData.Copy();
        //Fills the empty UserDefinedFieldName with timecheck field name. 
        foreach (DataRow drRow in dtCustomFieldData_Temp.Rows)
        {
            if (drRow["UserDefinedFieldName"].ToString() == string.Empty)
            {
                drRow["UserDefinedFieldName"] = drRow["FieldName"].ToString();
            }
        }
        //Filters the table with each UserDefinedFieldName and checks for duplicate.
        foreach (DataRow drRow in dtCustomFieldData_Temp.Rows)
        {
            dtCustomFieldData_Temp.DefaultView.RowFilter = "UserDefinedFieldName = '" + drRow["UserDefinedFieldName"].ToString() + "'";
            if (dtCustomFieldData_Temp.DefaultView.ToTable().Rows.Count > 1)
            {
                IsDuplicateExists = true;
                DuplicateFieldName = drRow["UserDefinedFieldName"].ToString();
                break;
            }
        }
        //If duplicate exists stops else proceeds with saving.
        if (IsDuplicateExists == true)
        {
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_DuplicateFieldNameExistsFor", ci) + "" + DuplicateFieldName + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("Alert", strScript);
        }
        else
        {
            //Inserts or updates the custom format based on the option type.
            objExportEventData.InsertUpdateCustomFormatForExportData(Optiontype, ddlDateFormat.SelectedValue, ddlTimeFormat.SelectedValue, ddlDateTimeFormat.SelectedValue, txtRootName.Text, txtFirstChildName.Text, DailyOrSummarizedData, Convert.ToInt16(ddlCompany.SelectedValue));
            //Deletes the custom data based on the option type before bulk insert.
            objExportEventData.DeleteCustomDataBasedOnOptionType(Optiontype, DailyOrSummarizedData, Convert.ToInt16(ddlCompany.SelectedValue));
            //Bulk Inserts the custom data based on the option type.
            objExportEventData.Insert_CustomFieldData(dtCustomFieldData);
            strScript = strScript + "<script language='javascript'>";
            //strScript = strScript + "alert('" + rm.GetString("Alert_SavedSuccessfully", ci) + "');window.close();if (window.opener && !window.opener.closed) {window.opener.location.reload();} ";
            strScript = strScript + "alert('" + rm.GetString("Alert_SavedSuccessfully", ci) + "');top.location.href = top.location + '?fl=1&sid=" + Session.SessionID + "';parent.$('#myModal').modal('hide');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("Alert", strScript);
        }
    }
    /// <summary>
    /// To clear all the entered datas.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnClear_Click(object sender, EventArgs e)
    {
    }
    /// <summary>
    /// Binds the grid based on the company selected
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (Optiontype == "All")
        {
            FillFieldNames_All();
        }
        else if (Optiontype == "OT")
        {
            FillFieldNames_OT();
        }
        else if (Optiontype == "Attendance")
        {
            FillFieldNames_Attendance();
        }
    }
    #endregion
}