using System;
using System.Configuration;
using System.Data;
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 : 28-Aug-2007
* Programmer      : Janakaraj.P
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          :
****************************************************************************************************************************/
public partial class Masters_TA_UI_Master_ShiftPatternView : Base.BasePage
{
    #region "Variable Declaration
    ResourceManager rm;
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    int PatternId;
    string gstrUserGroupName = string.Empty;
    DataSet ds_Nodays = new DataSet();
    DataSet ds_PatternName = new DataSet();
    Database db_con = DatabaseFactory.CreateDatabase("DBConnection");
    ShiftPatternEventData obj = new ShiftPatternEventData();
    ShiftRoasterEventData obj_ShiftRoaster = new ShiftRoasterEventData();
    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);
        //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;
        LoadStrings(ci);
        btn_Delete.OnClientClick = "javascript:return confirm('" + rm.GetString("Alert_ConfirmDelete", ci) + "')";
        btn_Restore.OnClientClick = "return confirm('" + rm.GetString("Alert_Areyousuretorestore", ci) + "')";
        btn_PermanentDelete.OnClientClick = "return confirm('" + rm.GetString("Alert_AreyouwantDeleteRecordPermanently", ci) + "')";
        gstrUserGroupName = Convert.ToString(Session["UserGroupName"]);
        // set user rights
        UserRights();
        loadcss();
        if (gstrUserGroupName == "SuperAdmin")
        {
            btn_Restore.Visible = true;
            btn_PermanentDelete.Visible = true;
        }
        else
        {
            btn_Restore.Visible = false;
            btn_PermanentDelete.Visible = false;
            lblDeleted.Visible = false;
            lblDeletedData.Visible = false;
        }
        PatternId = Convert.ToInt16(Request.QueryString["PatternId"]);
        GenerateHtmlTable();
        FillValues(Convert.ToInt16(ds_Nodays.Tables[0].Rows[0]["Shift_days"]));
        if (!IsPostBack)
        {
            objCommon.menu("ShiftMaster", "20");
        }
    }
    #endregion
    #region UserDefinedFunctions
    private void GenerateHtmlTable()
    {
        try
        {
            int numrows;
            int numcells;
            int i;
            int j;
            int count = 1;
            int cellcount;
            // Generate rows and cells
            ds_Nodays = GetNumberOfdays();
            numrows = Convert.ToInt16(ds_Nodays.Tables[0].Rows[0]["Shift_days"]);
            cellcount = Convert.ToInt16(ds_Nodays.Tables[0].Rows[0]["Shift_days"]);
            numcells = 1;
            if (numrows >= 5)
            {
                Table1.Style.Add("height", "230px");
                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");
                        Label lbl_Value = new Label();
                        lbl_Value.ID = "lbl" + count;
                        lbl_Value.Text = Convert.ToString(count); ;
                        lbl_Value.CssClass = "form-control";
                        c.CssClass = "col-md-12";
                        div1.Controls.Add(lbl_Value);
                        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 = GetPatternName();
            lblNoDays.Text = Convert.ToString(NoDays);
            ViewState["companyId"] = Convert.ToString(ds_Pattern.Tables[0].Rows[0]["Level_Id"]);
            lbl_OrgLevel.Text = Convert.ToString(ds_Pattern.Tables[0].Rows[0]["Name"]);
            lblPattern_Name.Text = Convert.ToString(ds_Pattern.Tables[0].Rows[0]["Pattern_Name"]);
            if (Convert.ToString(ds_Pattern.Tables[0].Rows[0]["Isdeleted"]) != "")
            {
                lblDeletedData.Text = Convert.ToString(ds_Pattern.Tables[0].Rows[0]["Isdeleted"]);
                if (lblDeletedData.Text == "True" || lblDeletedData.Text == rm.GetString("Grid_True", ci))
                {
                    btn_Delete.Visible = false;
                }
                else if (lblDeletedData.Text == "False" || lblDeletedData.Text == rm.GetString("Grid_False", ci))
                {
                    btn_Restore.Visible = false;
                }
                if (lblDeletedData.Text == "True")
                {
                    lblDeletedData.Text = rm.GetString("Grid_True", ci);
                }
                else if (lblDeletedData.Text == "False")
                {
                    lblDeletedData.Text = rm.GetString("Grid_False", ci);
                }
            }
            // 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]))
                    {
                        Label lblShiftName = new Label();
                        string LabelId = "lbl" + (i + 1);
                        lblShiftName = (Label)Table1.FindControl(LabelId);
                        lblShiftName.Text = Convert.ToString(ds_Shift.Tables[0].Rows[j]["Shift_ShortName"]);
                    }
                    //If the shift id is -1, placing the WeekOff short name from the web.config
                    if (Convert.ToString(ds_Pattern.Tables[0].Rows[0][dayShiftName]) == "-1")
                    {
                        Label lblShiftName = new Label();
                        string LabelId = "lbl" + (i + 1);
                        lblShiftName = (Label)Table1.FindControl(LabelId);
                        lblShiftName.Text = "<b>" + rm.GetString(Convert.ToString(ConfigurationManager.AppSettings["WeekOffShortName"]), ci) + "</b>";
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    private DataSet GetNumberOfdays()
    {
        DataSet ds = new DataSet();
        try
        {
            ds = obj.SelectPatternDetails(PatternId);
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString());
        }
        return ds;
    }
    private DataSet GetShiftName()
    {
        DataSet ds_ShiftName = new DataSet();
        try
        {
            ds_ShiftName = obj.ShiftName(0);
        }
        catch
        {
            //
        }
        return ds_ShiftName;
    }
    private DataSet GetPatternName()
    {
        try
        {
            ds_PatternName = obj.SelectPatternDetails(PatternId);
        }
        catch
        {
        }
        return ds_PatternName;
    }
    public bool CheckShiftPatternMapping()
    {
        bool checkDeleteFlag = true;
        DataSet ds_ShiftRoaster = new DataSet();
        try
        {
            ds_ShiftRoaster = obj_ShiftRoaster.SelectShiftRoaster(gstrUserGroupName, Convert.ToString(Session["LevelRights"]), Convert.ToInt16(Session["parentLevelId"]));
            for (int Rowcount = 0; Rowcount < ds_ShiftRoaster.Tables[0].Rows.Count; Rowcount++)
            {
                for (int i = 1; i <= 10; i++)
                {
                    string str_ShiftPattern = "Pattern" + i;
                    if (PatternId == Convert.ToInt16(Convert.ToString(ds_ShiftRoaster.Tables[0].Rows[Rowcount][str_ShiftPattern]).Trim()))
                    {
                        checkDeleteFlag = false;
                        base.Message(rm.GetString("Masters_ShiftPattern_Cannot_Modified", ci));
                        return false;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // 
        }
        return (checkDeleteFlag);
    }
    private bool checkshiftdelete()
    {
        bool checkShift = false;
        int shiftId, ShiftCount = 0;
        DataSet dsShift = obj.SelectPatternDetails(PatternId);
        if (dsShift.Tables[0].Rows.Count > 0)
        {
            int rowcounts = 3;
            //foreach (DataRow dRow in dsShift.Tables[0].Rows)
            for (rowcounts = 3; rowcounts < 34; rowcounts++)
            {
                shiftId = Convert.ToInt32(dsShift.Tables[0].Rows[0][rowcounts]);
                if (shiftId != -1 && shiftId != 0)
                {
                    ShiftCount = obj.CheckShiftPattern_Delete(shiftId);
                }
                if (ShiftCount > 0)
                {
                    checkShift = true;
                    break;
                }
            }
        }
        return checkShift;
    }
    //Getting Information from resource file and display it in label
    private void LoadStrings(CultureInfo ci)
    {
        lbl_OrganizationLevel.Text = rm.GetString("EntranceMaster_Company", 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);
        btn_Restore.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Restore", ci);
        btn_Modify.Text = rm.GetString("btn_Modify", ci);
        btn_Delete.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Delete", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        lblDeleted.Text = rm.GetString("DeleteStatus", ci);
        btn_PermanentDelete.Text = "&nbsp;&nbsp;" + rm.GetString("btn_PermanentDelete", ci);
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(20, Convert.ToInt32(Session["userGroup_Id"]), "");
        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {
            if (ds_Checkuser.Tables[0].Rows[0]["viewPrv"] == DBNull.Value || Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["viewPrv"]) != 1)
            {
                Response.Redirect("TA_UI_Master_ShiftPattern.aspx");
            }
            if (ds_Checkuser.Tables[0].Rows[0]["modifyPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["modifyPrv"]) == 1)
            {
                this.btn_Modify.Visible = true;
            }
            else
            {
                this.btn_Modify.Visible = false;
            }
            if (ds_Checkuser.Tables[0].Rows[0]["deletePrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["deletePrv"]) == 1)
            {
                this.btn_Delete.Visible = true;
                this.btn_PermanentDelete.Visible = true;
                this.btn_Restore.Visible = true;
            }
            else
            {
                this.btn_Delete.Visible = false;
                this.btn_PermanentDelete.Visible = false;
                this.btn_Restore.Visible = false;
            }
        }
        else
        {
            Response.Redirect("MasterLandingPage.aspx");
        }
    }
    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
        htmlShiftPattern.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";
        }
        else
        {
            //htmlShiftPattern.Attributes.Add("dir", "rtl");
            //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";
            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";
        }
    }
    #endregion
    #region ButtonEvents
    protected void btn_Delete_Click(object sender, EventArgs e)
    {
        bool checkDeleteFlag = true;
        // no need to check shift while deleting shift pattern  
        DataSet ds_ShiftRoaster = new DataSet();
        ds_ShiftRoaster = obj_ShiftRoaster.SelectShiftRoaster(gstrUserGroupName, Convert.ToString(Session["LevelRights"]), Convert.ToInt16(Session["parentLevelId"]));
        if (ds_ShiftRoaster.Tables[0].Rows.Count > 0)
        {
            for (int Rowcount = 0; Rowcount < ds_ShiftRoaster.Tables[0].Rows.Count; Rowcount++)
            {
                for (int i = 1; i <= 10; i++)
                {
                    string str_ShiftPattern = "Pattern" + i;
                    if (PatternId == Convert.ToInt16(Convert.ToString(ds_ShiftRoaster.Tables[0].Rows[Rowcount][str_ShiftPattern]).Trim()))
                    {
                        checkDeleteFlag = false;
                        base.Message(rm.GetString("Masters_ShiftPattern_Cannot_Delete", ci));
                        return;
                    }
                }
            }
        }
        else
        {
            obj.DeleteShiftPattern(PatternId);
            base.MessageWithRedirect(rm.GetString("Alert_ShiftPatterndeletedsuccessfully", ci), "TA_UI_Master_ShiftPattern.aspx");
        }
    }
    protected void btn_Modify_Click(object sender, EventArgs e)
    {
        bool checkDeleteFlag = true;
        checkDeleteFlag = CheckShiftPatternMapping();
        if (checkDeleteFlag == false)
        {
            base.Message(rm.GetString("Masters_ShiftPattern_Cannot_Modified", ci));
        }
        else
        {
            Response.Redirect("TA_UI_Master_ShiftPatternModify.aspx?PatternId=" + Convert.ToInt16(Request.QueryString["PatternId"]) + "&companyId=" + ViewState["companyId"] + "");
        }
    }
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Master_ShiftPattern.aspx");
    }
    /// <summary>
    /// Handles the Click event of the btn_Restore control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btn_Restore_Click(object sender, EventArgs e)
    {
        int count = 0;
        count = obj.CheckShiftPattern_Restore(PatternId);
        if (count > 0)
        {
            base.Message(rm.GetString("Message_Cannot_Restore", ci));
        }
        else
        {
            obj.RestoreShiftPattern(Convert.ToString(PatternId));
            base.MessageWithRedirect(rm.GetString("Alert_ShiftPatternrestoredsuccessfully", ci), "TA_UI_Master_ShiftPattern.aspx");
        }
    }
    /// <summary>
    /// Handles the Click event of the btn_PermanentDelete control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btn_PermanentDelete_Click(object sender, EventArgs e)
    {
        bool checkDeleteFlag = true;
        DataSet ds_ShiftRoaster = new DataSet();
        try
        {
            ds_ShiftRoaster = obj_ShiftRoaster.SelectShiftRoaster(gstrUserGroupName, Convert.ToString(Session["LevelRights"]), Convert.ToInt16(Session["parentLevelId"]));
            for (int Rowcount = 0; Rowcount < ds_ShiftRoaster.Tables[0].Rows.Count; Rowcount++)
            {
                for (int i = 1; i <= 10; i++)
                {
                    string str_ShiftPattern = "Pattern" + i;
                    if (PatternId == Convert.ToInt16(Convert.ToString(ds_ShiftRoaster.Tables[0].Rows[Rowcount][str_ShiftPattern]).Trim()))
                    {
                        checkDeleteFlag = false;
                        base.Message(rm.GetString("Masters_ShiftPattern_Cannot_Delete", ci));
                        return;
                    }
                }
            }
            if (checkDeleteFlag == false)
            {
                base.Message(rm.GetString("Masters_ShiftPattern_Cannot_Delete", ci));
            }
            else
            {
                obj.PermanentDeleteShiftPattern(PatternId);
                base.MessageWithRedirect(rm.GetString("Alert_ShiftPatterndeletedsuccessfully", ci), "TA_UI_Master_ShiftPattern.aspx");
            }
        }
        catch
        {
            //
        }
    }
    #endregion
}