using System;
using System.Collections;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
public partial class Masters_TA_UI_Master_ShiftRoasterModify : Base.BasePage
{
    #region "Variable Declaration"
    int RoasterId, Nodays, numrows, numcells, count = 1, intCompanyId;
    string Rid;
    ShiftRoasterEventData obj_ShiftRoaster = new ShiftRoasterEventData();
    DataSet ds_Shift = new DataSet();
    DataSet ds_Roaster = new DataSet();
    DataSet ds_ShiftPattern = new DataSet();
    Hashtable hs = new Hashtable();
    cls_Common objCommon = new cls_Common();
    ResourceManager rm;
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    ShiftEvenData objShift = new ShiftEvenData();
    string gstrUserGroupName = string.Empty;
    //string strPatternIds;
    #endregion
    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();
        if (!Page.IsPostBack)
        {
            txt_RoasterName.Focus();
            RoasterId = Convert.ToInt16(Request.QueryString["Id"]);
            Nodays = Convert.ToInt16(Request.QueryString["Nodays"]);
            intCompanyId = Convert.ToInt16(Request.QueryString["companyId"]);
            CompanyBinding();
            ViewState["companyId"] = intCompanyId;
            ViewState["RoasterId"] = RoasterId;
            ViewState["Nodays"] = Nodays;
            //Shows ShiftRoaster Details 
            ViewRoasterDetails();
            //Generate Table with dynamic dropdownlist
            GenerateTable(Nodays);
            //Alerts
            string strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_SelectShiftPattern") + "','" + rm.GetString("Alert_ConfirmSave") + "');";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
            objCommon.menu("ShiftMaster", "69");
        }
    }
    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 = '" + intCompanyId + "'";
                if (dsCompany.Tables[0].DefaultView.Count > 0)
                {
                    lblCompanyName.Text = dsCompany.Tables[0].DefaultView[0]["CompanyName"].ToString();
                }
            }
        }
    }
    //Getting Information from resource file and display it in label
    private void LoadStrings(CultureInfo ci)
    {
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lbl_Header.Text = rm.GetString("Masters_ShiftRoster", ci);
        lbl_RoasterName.Text = rm.GetString("ShiftRoster_Name", ci);
        lbl_Nopatterns.Text = rm.GetString("ShiftRoster_NofPatterns", ci);
        RequiredFieldValidator1.ErrorMessage = rm.GetString("Req_ShiftRoasterName", ci);
        RequiredFieldValidator2.ErrorMessage = rm.GetString("Req_NumberofPatterns", ci);
        lblCompany.Text = rm.GetString("EntranceMaster_Company", ci);
        btn_Save.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btn_Back.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        ddl_Nopatterns.Items[0].Text = rm.GetString("Select", ci);
    }
    private void GenerateTable(int rows)
    {
        try
        {
            // Generate rows and cells
            if (ddl_Nopatterns.SelectedValue != "-Select-")
                numrows = Convert.ToInt16(ddl_Nopatterns.SelectedValue);
            else
                numrows = rows;
            if (numrows != 0)
            {
                tbl_ShiftRoaster.Style.Add("border", "1px solid #c5dffc;");
            }
            if (numrows == 0)
            {
                tbl_ShiftRoaster.Style.Add("height", "0px");
                tbl_ShiftRoaster.Style.Add("border", "none");
            }
            else if (numrows == 1 || numrows == 2)
            {
                tbl_ShiftRoaster.Style.Add("height", "80px");
            }
            else if (numrows == 3 || numrows == 4)
            {
                tbl_ShiftRoaster.Style.Add("height", "120px");
            }
            else if (numrows == 5 || numrows == 6)
            {
                tbl_ShiftRoaster.Style.Add("height", "160px");
            }
            else if (numrows == 7 || numrows == 8)
            {
                tbl_ShiftRoaster.Style.Add("height", "200px");
            }
            else if (numrows == 9 || numrows == 10)
            {
                tbl_ShiftRoaster.Style.Add("height", "210px");
            }
            else
            {
                tbl_ShiftRoaster.Style.Add("height", "207px");
                tbl_ShiftRoaster.Style.Add("border", "1px solid #c5dffc;");
            }
            numcells = 1;
            if (numrows >= 1)
                if ((numrows % 1) == 0)
                    numrows = numrows / 1;
                else
                    numrows = numrows + 1;
            else
                numrows = 1;
            //Generate Rows and Columns based on the selected value
            if (ddl_Nopatterns.SelectedValue != "-Select-")
            {
                for (int j = 1; j <= numrows; j++)
                {
                    //Create Dynamic Rows
                    TableRow r = new TableRow();
                    for (int i = 1; i <= numcells; i++)
                    {
                        if (count <= Convert.ToInt16(ddl_Nopatterns.SelectedValue))
                        {
                            //Create Dynamic dropdowns
                            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", ci) + "&nbsp;&nbsp;" + count));
                            }
                            else
                            {
                                div.Controls.Add(new LiteralControl(rm.GetString("ShiftPattern", ci) + "&nbsp;&nbsp;" + count));
                            }
                            tbl_ShiftRoaster.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_SRoaster = new DropDownList();
                            ddl_SRoaster.CssClass = "form-control select2";
                            ddl_SRoaster.ID = "ddl_SRoaster" + count;
                            //Fiil dorpdown with Shiftpatttern Name
                            ddl_SRoaster.DataSource = FillDropDown();
                            ddl_SRoaster.DataValueField = "ShiftPattern_Id";
                            ddl_SRoaster.DataTextField = "Pattern_Name";
                            ddl_SRoaster.DataBind();
                            //Adding Select in dropdown 
                            ListItem liSelect = new ListItem();
                            liSelect.Text = rm.GetString("Select", ci);
                            liSelect.Value = "-Select-";
                            ddl_SRoaster.Items.Insert(0, liSelect);
                            ddl_SRoaster.Items[0].Value = "0";
                            foreach (ListItem item in ddl_SRoaster.Items)
                            {
                                item.Attributes.Add("title", item.Text);
                            }
                            if (!Page.IsPostBack)
                                ddl_SRoaster.SelectedValue = ShowRoasterValues(count);
                            //Update the dataset with new value
                            ddl_SRoaster.Attributes.Add("onchange", "CheckShift(this," + count + "," + Convert.ToInt16(ddl_Nopatterns.SelectedValue) + ");changeShiftRoaster(" + count + ",this.id)");
                            div1.Controls.Add(ddl_SRoaster);
                            tbl_ShiftRoaster.Controls.Add(div1);
                            tbl_ShiftRoaster.Controls.Add(new LiteralControl("<div class='col-md-1'></div>"));
                            count = count + 1;
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    private DataSet FillDropDown()
    {
        //Fills the dropdowns with Shift Name        
        try
        {
            ds_Shift = obj_ShiftRoaster.SelectShiftPatternForShiftRoster(Convert.ToInt16(Request.QueryString["companyId"]));
        }
        catch
        {
            //
        }
        return ds_Shift;
    }
    /// <summary>
    /// Function Returns Selected ShiftroasterIds
    /// </summary>
    /// <param name="count"></param>
    /// <returns>String </returns>
    private string ShowRoasterValues(int count)
    {
        try
        {
            ds_Roaster = obj_ShiftRoaster.GetShiftRoasterDetailsById(Convert.ToInt16(ViewState["RoasterId"]));
            ds_ShiftPattern = obj_ShiftRoaster.SelectShiftPattern(gstrUserGroupName, Convert.ToString(Session["LevelRights"]), Convert.ToInt16(Session["parentLevelId"]));
            string strCol = "Pattern" + count;
            string value = ds_Roaster.Tables[0].Rows[0][strCol].ToString();
            foreach (DataRow dr in ds_ShiftPattern.Tables[0].Rows)
            {
                if (dr["ShiftPattern_Id"].ToString().Trim() == value.ToString().Trim())
                {
                    Rid = Convert.ToString(dr["ShiftPattern_Id"]);
                    return Rid;
                }
            }
        }
        catch
        {
            //
        }
        return Rid;
    }
    /// <summary>
    /// Shows ShiftRoaster Details In dropdown
    /// </summary>
    private void ViewRoasterDetails()
    {
        ds_Roaster = obj_ShiftRoaster.GetShiftRoasterDetailsById(Convert.ToInt16(ViewState["RoasterId"]));
        txt_RoasterName.Text = ds_Roaster.Tables[0].Rows[0]["ShiftRoaster_Name"].ToString();
        ddl_Nopatterns.SelectedValue = Convert.ToString(ds_Roaster.Tables[0].Rows[0]["NumberOfPatterns"]);
        Session["RoasterDetails"] = ds_Roaster;
    }
    protected void ddl_Nopatterns_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddl_Nopatterns.SelectedValue != "-Select-")
            GenerateTable(Convert.ToInt16(ddl_Nopatterns.SelectedValue));
    }
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        try
        {
            GenerateTable(Convert.ToInt16(ddl_Nopatterns.SelectedValue));
            //Checking for duplicate value
            if (obj_ShiftRoaster.CheckShiftRoasterNameUpdate(Convert.ToInt32(ViewState["companyId"]), txt_RoasterName.Text.Trim().Replace("'", "''"), Convert.ToInt16(ViewState["RoasterId"])) == 0)
            {
                ds_Roaster = (DataSet)Session["RoasterDetails"];
                ds_Roaster.Tables[0].Rows[0]["NumberOfPatterns"] = Convert.ToInt16(ddl_Nopatterns.SelectedValue);
                ds_Roaster.Tables[0].Rows[0]["ShiftRoaster_Name"] = txt_RoasterName.Text.Trim().Replace("'", "''");
                // Update the Shiftroaster Details
                obj_ShiftRoaster.UpdateShiftRoaster(Convert.ToInt32(ViewState["companyId"]), Convert.ToInt16(ViewState["RoasterId"]), ds_Roaster.Tables[0].Rows[0]["ShiftRoaster_Name"].ToString(), Convert.ToInt16(ds_Roaster.Tables[0].Rows[0]["NumberOfPatterns"]), Convert.ToInt32(ds_Roaster.Tables[0].Rows[0]["Pattern1"]), Convert.ToInt32(ds_Roaster.Tables[0].Rows[0]["Pattern2"]), Convert.ToInt32(ds_Roaster.Tables[0].Rows[0]["Pattern3"]),
                                                 Convert.ToInt32(ds_Roaster.Tables[0].Rows[0]["Pattern4"]), Convert.ToInt32(ds_Roaster.Tables[0].Rows[0]["Pattern5"]), Convert.ToInt32(ds_Roaster.Tables[0].Rows[0]["Pattern6"]), Convert.ToInt32(ds_Roaster.Tables[0].Rows[0]["Pattern7"]), Convert.ToInt32(ds_Roaster.Tables[0].Rows[0]["Pattern8"]),
                                                 Convert.ToInt32(ds_Roaster.Tables[0].Rows[0]["Pattern9"]), Convert.ToInt32(ds_Roaster.Tables[0].Rows[0]["Pattern10"]), Session["EmpAutoID"].ToString());
                string strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_Shiftrostersavedsuccessfully", ci) + "');";
                strScript = strScript + "location.replace('TA_UI_Master_ShiftRoaster.aspx');";
                strScript = strScript + "</script>";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_Shiftrosteralreadyexists", ci) + "');", true);
            }
        }
        catch
        {            //
        }
    }
    protected void btn_Back_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Master_ShiftRoaster.aspx");
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(69, Convert.ToInt32(Session["userGroup_Id"]), "modifyPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("MasterLandingPage.aspx");
        }
    }
}
