using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Web.UI.HtmlControls;
/****************************************************************************************************************************
* Project Name    : TimeCheck                                         Started Date  : 12-Aug-2007
* Module          : Shift Pattern                                     Last Modified : 10-Aug-2007
* Programmer      : Janakaraj.P
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          :
****************************************************************************************************************************/
public partial class Masters_TA_UI_Master_ShiftPatternModify : Base.BasePage
{
    ResourceManager rm;
    //get the culture info to set the language
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    int PatternId, companyId;
    DataSet ds_Nodays = new DataSet();
    Database db_con = DatabaseFactory.CreateDatabase("DBConnection");
    ShiftPatternEventData obj = new ShiftPatternEventData();
    ShiftEvenData objShift = new ShiftEvenData();
    DataSet ds_Shift = new DataSet();
    cls_Common objCommon = new cls_Common();
    string gstrUserGroupName = string.Empty;
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        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);
        gstrUserGroupName = Convert.ToString(Session["UserGroupName"]);
        // set user rights
        UserRights();
        PatternId = Convert.ToInt16(Request.QueryString["PatternId"]);
        hdf_ShiftPatternId.Value = Convert.ToString(Request.QueryString["PatternId"]);
        if (Request.QueryString["companyId"] == null)
            companyId = 0;
        else
            companyId = Convert.ToInt16(Request.QueryString["companyId"]);
        if (!Page.IsPostBack)
        {
            lblPattern_Name.Focus();
            CompanyBinding();
            ds_Nodays = GetNumberOfdays();
            int numrows, cellcount;
            numrows = Convert.ToInt16(ds_Nodays.Tables[0].Rows[0]["Shift_days"]);
            cellcount = Convert.ToInt16(ds_Nodays.Tables[0].Rows[0]["Shift_days"]);
            GenerateHtmlTable(numrows, cellcount);
            FillValues(Convert.ToInt16(ds_Nodays.Tables[0].Rows[0]["Shift_days"]));
            //Alerts
            string strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
            strSetAlert = strSetAlert + "SetPatternName('" + rm.GetString("Alert_PatternNameAlreadyExists", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_ClickGobuttontoGenerateDays") + "','" + rm.GetString("ReqField_SelectDay") + "','" + rm.GetString("Alert_ConfirmSave") + "');";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
            objCommon.menu("ShiftMaster", "20");
        }
    }
    private void CompanyBinding()
    {
        DataSet dsCompany = new DataSet();
        dsCompany = objShift.SelectCompany(gstrUserGroupName, Convert.ToString(Session["LevelRights"]), 0);
        if (dsCompany != null)
        {
            if (dsCompany.Tables[0].Rows.Count > 0)
            {
                dsCompany.Tables[0].DefaultView.RowFilter = "CompanyId = '" + companyId + "'";
                if (dsCompany.Tables[0].DefaultView.Count > 0)
                {
                    lblCompanyName.Text = Convert.ToString(dsCompany.Tables[0].DefaultView[0]["CompanyName"]);
                }
            }
        }
    }
    private void GenerateHtmlTable(int numrows, int cellcount)
    {
        try
        {
            //int numrows;
            int numcells;
            int i;
            int j;
            int count = 1;
            numcells = 1;
            if (numrows != 0)
            {
                Table1.Style.Add("border", "1px solid #c5dffc;");
            }
            if (numrows == 0)
            {
                Table1.Style.Add("height", "0px");
                Table1.Style.Add("border", "none");
            }
            else if (numrows == 1 || numrows == 2)
            {
                Table1.Style.Add("height", "80px");
            }
            else if (numrows == 3 || numrows == 4)
            {
                Table1.Style.Add("height", "120px");
            }
            else if (numrows == 5 || numrows == 6)
            {
                Table1.Style.Add("height", "160px");
            }
            else if (numrows == 7 || numrows == 8)
            {
                Table1.Style.Add("height", "200px");
            }
            else if (numrows == 9 || numrows == 10)
            {
                Table1.Style.Add("height", "210px");
            }
            else
            {
                Table1.Style.Add("height", "207px");
                Table1.Style.Add("border", "1px solid #c5dffc;");
            }
            if (numrows >= 1)
                if ((numrows % 1) == 0)
                    numrows = numrows / 1;
                else
                    numrows = numrows + 1;
            else
                numrows = 1;
            //Generate Rows and Cols based on the selected value
            for (j = 1; j <= numrows; j++)
            {
                TableRow r = new TableRow();
                for (i = 1; i <= numcells; i++)
                {
                    if (count <= cellcount)
                    {
                        TableCell c = new TableCell();
                        HtmlGenericControl div = new HtmlGenericControl("div");
                        div.Attributes.Add("class", "col-md-2");
                        div.Style.Add("padding-top", "10px");
                        if (count < 10)
                        {
                            div.Controls.Add(new LiteralControl(rm.GetString("ShiftPattern_Day", ci) + " " + count));
                        }
                        else
                        {
                            div.Controls.Add(new LiteralControl(rm.GetString("ShiftPattern_Day", ci) + " " + count));
                        }
                        Table1.Controls.Add(div);
                        HtmlGenericControl div1 = new HtmlGenericControl("div");
                        div1.Attributes.Add("class", "col-md-3");
                        div1.Style.Add("padding-top", "10px");
                        div1.Style.Add("padding-left", "14px");
                        div1.Style.Add("padding-right", "14px");
                        DropDownList ddl_SPattern = new DropDownList();
                        ddl_SPattern.ID = "ddl_Pattern" + count;
                        ddl_SPattern.CssClass = "form-control select2";                        
                        ddl_SPattern.DataSource = FillDropDown();
                        ddl_SPattern.DataTextField = "Shift_ShortName";
                        ddl_SPattern.DataValueField = "Shift_Id";
                        ddl_SPattern.DataBind();
                        ListItem liSelect = new ListItem();
                        liSelect.Text = rm.GetString("Select", ci);
                        liSelect.Value = "-Select-";
                        ddl_SPattern.Items.Insert(0, liSelect);
                        ddl_SPattern.Items[0].Value = "0";
                        ddl_SPattern.Items.Insert(ddl_SPattern.Items.Count, rm.GetString(Convert.ToString(ConfigurationManager.AppSettings["WeekOffShortName"]), ci));
                        ddl_SPattern.Items[ddl_SPattern.Items.Count - 1].Value = "-1";
                        foreach (ListItem item in ddl_SPattern.Items)
                        {
                            item.Attributes.Add("title", item.Text);
                        }
                        ddl_SPattern.Attributes.Add("onchange", "CheckShift(this," + count + "," + Convert.ToInt16(ddl_NoDays.SelectedValue) + ");changeShiftPattern(" + count + ", this.id )");
                        div1.Controls.Add(ddl_SPattern);
                        Table1.Controls.Add(div1);
                        Table1.Controls.Add(new LiteralControl("<div class='col-md-1'></div>"));
                        count = count + 1;
                    }
                }
            }
        }
        catch
        {
            //
        }
    }
    private void FillValues(int NoDays)
    {
        try
        {
            DataSet ds_Shift = GetShiftName();
            DataSet ds_Pattern;
            lblNoDays.Text = Convert.ToString(NoDays);
            if (!IsPostBack)
            {
                ds_Pattern = GetPatternName();
                ddl_NoDays.SelectedValue = lblNoDays.Text;
            }
            else
                ds_Pattern = (DataSet)Session["ds_Pattern"];
            Session["ds_Pattern"] = ds_Pattern;
            //ddlCompany.SelectedValue = ds_Pattern.Tables[0].Rows[0]["Level_Id"].ToString();
            lblPattern_Name.Text = Convert.ToString(ds_Pattern.Tables[0].Rows[0]["Pattern_Name"]);
            // Added by: Abul on 17th July
            int i = 0; // for iterating the total selected days
            int j = 0; // for iterating the shift patterns
            for (i = 0; i < NoDays; i++) //iterating the total days
            {
                for (j = 0; j < ds_Shift.Tables[0].Rows.Count; j++) // iterating the total shifts
                {
                    string dayShiftName;
                    dayShiftName = "Day" + (i + 1) + "_" + "Shift";
                    if (Convert.ToString(ds_Shift.Tables[0].Rows[j]["Shift_Id"]) == Convert.ToString(ds_Pattern.Tables[0].Rows[0][dayShiftName]))
                    {
                        DropDownList ddl_SPattern = new DropDownList();
                        string LabelId = "ddl_Pattern" + (i + 1);
                        ddl_SPattern = (DropDownList)Table1.FindControl(LabelId);
                        ddl_SPattern.SelectedValue = Convert.ToString(ds_Pattern.Tables[0].Rows[0][dayShiftName]);
                        ddl_SPattern.Attributes.Add("onchange", "CheckShift(this," + i + "," + Convert.ToInt16(ddl_NoDays.SelectedValue) + ");changeShiftPattern(" + (i + 1) + ", '" + Convert.ToString(ddl_SPattern.ClientID) + "' )");
                    }
                    if (Convert.ToString(ds_Pattern.Tables[0].Rows[0][dayShiftName]) == "-1")
                    {
                        DropDownList ddl_SPattern = new DropDownList();
                        string LabelId = "ddl_Pattern" + (i + 1);
                        ddl_SPattern = (DropDownList)Table1.FindControl(LabelId);
                        ddl_SPattern.SelectedValue = "-1";
                        ddl_SPattern.Attributes.Add("onchange", "CheckShift(this," + i + "," + Convert.ToInt16(ddl_NoDays.SelectedValue) + ");changeShiftPattern(" + (i + 1) + ", '" + Convert.ToString(ddl_SPattern.ClientID) + "' )");
                        //ddl_SPattern.Attributes.Add("onchange", "CheckShift(this," + i + "," + Convert.ToInt16(ddl_NoDays.SelectedValue) + ");");
                    }
                }
            }
            // End of adding new code: To place the shift names to the dynamically created labels.
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    private DataSet GetNumberOfdays()
    {
        DataSet ds = new DataSet();
        try
        {
            ds = obj.SelectPatternDetails(PatternId);
        }
        catch
        {
        }
        return ds;
    }
    private DataSet GetShiftName()
    {
        DataSet ds_ShiftName = new DataSet();
        try
        {
            ds_ShiftName = obj.ShiftName(0);
        }
        catch
        {
            //
        }
        return ds_ShiftName;
    }
    private DataSet GetPatternName()
    {
        DataSet ds_PatternName = new DataSet();
        try
        {
            ds_PatternName = obj.SelectPatternDetails(PatternId);
        }
        catch
        {
        }
        return ds_PatternName;
    }
    protected void btn_Delete_Click(object sender, EventArgs e)
    {
        try
        {
            PatternId = Convert.ToInt16(Request.QueryString["PatternId"]);
            obj.DeleteShiftPattern(PatternId);
            string strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_ShiftPatterndeletedsuccessfully", ci) + "');";
            strScript = strScript + "location.replace('TA_UI_Master_ShiftPattern.aspx');";
            strScript = strScript + "</script>";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString());
        }
    }
    protected void btn_Modify_Click(object sender, EventArgs e)
    {
        try
        {
            int totalDays = Convert.ToInt32(ddl_NoDays.SelectedValue);
            PatternId = Convert.ToInt16(Request.QueryString["PatternId"]);
            DataSet dsShiftPattern = new DataSet();
            dsShiftPattern = (DataSet)Session["ds_Pattern"];
            int i;
            // Updating the Other items in the DataSet to be 0 other than the selected one.
            for (i = 0; i <= 31; i++)
            {
                if (i > totalDays)
                {
                    string ColName = "Day" + (i) + "_Shift";
                    dsShiftPattern.Tables[0].Rows[0][ColName] = 0;
                }
            }
            // Checking for the Null Selection in the DropDownList values.
            for (i = 1; i <= totalDays; i++)
            {
                string ColName = "Day" + (i) + "_Shift";
                if (Convert.ToInt32(dsShiftPattern.Tables[0].Rows[0][ColName]) == 0)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_Selectallthevaluesforallthedates", ci) + "');", true);
                    LoadNew();
                    return;
                }
            }
            dsShiftPattern.Tables[0].Rows[0]["Pattern_Name"] = lblPattern_Name.Text.Trim();
            dsShiftPattern.Tables[0].Rows[0]["Shift_days"] = Convert.ToInt32(ddl_NoDays.SelectedValue);
            SqlDataAdapter da = new SqlDataAdapter("select * from TA_Tbl_ShiftPattern where ShiftPattern_Id = " + PatternId + "", obj.opebDB());
            SqlCommandBuilder sqlcmdbldr = new SqlCommandBuilder(da);
            da.Update(dsShiftPattern.Tables[0]);
            string strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_ShiftPatternsavedsuccessfully", ci) + "');";
            strScript = strScript + "location.replace('TA_UI_Master_ShiftPattern.aspx');";
            strScript = strScript + "</script>";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString());
        }
        finally
        {
            obj.closeDB();
        }
    }
    private DataSet FillDropDown()
    {
        //Fills the dropdowns with Shift Name
        try
        {
            string usergroupname = string.Empty;
            ds_Shift = obj.SelectShiftForShiftPattern(companyId);
            foreach (DataRow drRow in ds_Shift.Tables[0].Rows)
            {
                switch (Convert.ToString(drRow["Shift_ShortName"]))
                {
                    case "No Shift":
                        drRow["Shift_ShortName"] = rm.GetString("Caption_NoShift", ci);
                        break;
                }
            }
        }
        catch
        {
        }
        return ds_Shift;
    }
    protected void ddl_NoDays_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadNew();
    }
    public void LoadNew()
    {
        int defaultDayCount, newDayCount;
        ds_Nodays = GetNumberOfdays();
        defaultDayCount = Convert.ToInt16(ds_Nodays.Tables[0].Rows[0]["Shift_days"]);
        newDayCount = Convert.ToInt32(ddl_NoDays.SelectedValue);
        GenerateHtmlTable(Convert.ToInt32(ddl_NoDays.SelectedValue), Convert.ToInt32(ddl_NoDays.SelectedValue));
        if (newDayCount > defaultDayCount)
            FillValues(defaultDayCount);
        else
            FillValues(newDayCount);
    }
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        PatternId = Convert.ToInt16(Request.QueryString["PatternId"]);
        Response.Redirect("TA_UI_Master_ShiftPattern.aspx");
    }
    //Getting Information from resource file and display it in label
    private void LoadStrings(CultureInfo ci)
    {
        lblCompany.Text = rm.GetString("EntranceMaster_Company", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lbl_PatternName.Text = rm.GetString("ShiftPattern_PatternName", ci);
        lbl_NumberOfDays.Text = rm.GetString("ShiftPattern_NumberOfDays", ci);
        lbl_HeaderShiftPattern.Text = rm.GetString("Masters_ShiftPattern", ci);
        RequiredFieldValidator1.ErrorMessage = rm.GetString("PatternName_Enter", ci);
        RequiredFieldValidator2.ErrorMessage = rm.GetString("Validator_SelectNumberOfDays", ci);
        butSelect.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Go", ci);
        btn_Modify.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        ddl_NoDays.Items[0].Text = rm.GetString("Select", ci);
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(20, Convert.ToInt32(Session["userGroup_Id"]), "modifyPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("MasterLandingPage.aspx");
        }
        else
        {
            //   
        }
    }
    protected void butSelect_Click(object sender, EventArgs e)
    {
        int defaultDayCount, newDayCount;
        ds_Nodays = GetNumberOfdays();
        defaultDayCount = Convert.ToInt16(ds_Nodays.Tables[0].Rows[0]["Shift_days"]);
        newDayCount = Convert.ToInt32(ddl_NoDays.SelectedValue);
        GenerateHtmlTable(Convert.ToInt32(ddl_NoDays.SelectedValue), Convert.ToInt32(ddl_NoDays.SelectedValue));
        if (newDayCount > defaultDayCount)
            FillValues(defaultDayCount);
        else
            FillValues(newDayCount);
    }
}