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_FieldNameForORCL : 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 + "opener.location.href = opener.location + '?fl=1&sid=" + Session.SessionID + "';";
            str = str + "window.close();";
            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") + "')) window.close();";
        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");
        if (!IsPostBack)
        {
            CompanyBinding();
            if (Optiontype == "All")
            {
                FillFieldNames_All();
            }
            else if (Optiontype == "OT")
            {
                FillFieldNames_OT();
            }
            else if (Optiontype == "Attendance")
            {
                FillFieldNames_Attendance();
            }
            else if (Optiontype == "Leave")
            {
                FillFieldNames_Leave();
            }
        }
    }
    #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 = rm.GetString("btn_Save", ci);
        btnCancel.Text = rm.GetString("btn_Cancel", ci);
    }
    /// <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("ot_type");
            dsFieldNames.Tables[0].Rows.Add("ot_hours");
            //dsFieldNames.Tables[0].Rows.Add("remarks");
        }
        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("attn_code");
            dsFieldNames.Tables[0].Rows.Add("no_of_days");
            //dsFieldNames.Tables[0].Rows.Add("remarks");
        }
        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_Leave()
    {
        //To fill custom formats.
        FillCustomFields("Leave");
        //To fill field names.
        dsFieldNames = objExportEventData.GetCustomFieldNamesForExportData("Leave", 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");
            if (DailyOrSummarizedData == "DailyData")
            {
                dsFieldNames.Tables[0].Rows.Add("Employee_Code_Id");
                dsFieldNames.Tables[0].Rows.Add("Leave_FromDate");
                dsFieldNames.Tables[0].Rows.Add("Leave_Todate");
                dsFieldNames.Tables[0].Rows.Add("LeaveType");
                dsFieldNames.Tables[0].Rows.Add("NoOfDays");
                dsFieldNames.Tables[0].Rows.Add("TransactionType");
            }
            else
            {
                dsFieldNames.Tables[0].Rows.Add("Employee_Code_Id");
                //dsFieldNames.Tables[0].Rows.Add("EmployeeName");
                dsFieldNames.Tables[0].Rows.Add("NoOfDays");
            }
        }
        if (dsFieldNames != null)
        {
            if (dsFieldNames.Tables[0].Rows.Count > 0)
            {
                gvFieldData.DataSource = dsFieldNames.Tables[0];
                gvFieldData.DataBind();
                //if (DailyOrSummarizedData != "SummarizedData")
                //{
                //    gvFieldData.Rows[2].Visible = false;
                //    gvFieldData.Rows[3].Visible = false;
                //}
            }
        }
        //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
        {
            objExportEventData.InsertUpdateCustomFormatForExportData(Optiontype, ddlDateFormat.SelectedValue, ddlTimeFormat.SelectedValue, ddlDateTimeFormat.SelectedValue, txtRootName.Text, txtFirstChildName.Text, DailyOrSummarizedData, Convert.ToInt16(ddlCompany.SelectedValue));
            objExportEventData.DeleteCustomDataBasedOnOptionType(Optiontype, DailyOrSummarizedData, Convert.ToInt16(ddlCompany.SelectedValue));
            objExportEventData.Insert_CustomFieldData(dtCustomFieldData);
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_SavedSuccessfully", ci) + "');opener.focus();opener.location.href = opener.location + '?fl=1&sid=" + Session.SessionID + "';window.close();";
            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 (ddlCompany.SelectedValue != "-Select-")
        //{
        if (Optiontype == "All")
        {
            FillFieldNames_All();
        }
        else if (Optiontype == "OT")
        {
            FillFieldNames_OT();
        }
        else if (Optiontype == "Attendance")
        {
            FillFieldNames_Attendance();
        }
        else if (Optiontype == "Leave")
        {
            FillFieldNames_Leave();
        }
        //}
        //else
        //{
        //    gvFieldData.DataSource = "";
        //    gvFieldData.DataBind();
        //}
    }
    #endregion
}
