using System;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DevExpress.Web;
/****************************************************************************************************************************
* Project Name    : TimeCheck                                         Started Date  : 12-Aug-2007
* Module          : Organisation Levels                               Last Modified : 21-Aug-2007
* Programmer      : Senthil Kumar NP
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          :
****************************************************************************************************************************/
public partial class Masters_TA_UI_Master_LevelDetails : Base.BasePage
{
    #region VariableDeclaration
    ResourceManager rm;
    CultureInfo ci;
    int gintParentId = 1;
    org_levelsEventData selectLevel = new org_levelsEventData();
    string source_Language;
    string strScript = string.Empty;
    cls_Common objCommon = new cls_Common();
    int count = 0;
    int CurrentPageTotalRecords = 0;
    bool s = false;
    int levelid = 0;
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        grvLevel.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        //get the culture info to set the 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);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "RestoreAlert('" + rm.GetString("Alert_Norecordsfound", ci) + "','" +
            rm.GetString("Alert_Areyousuretorestore", ci) + "','" +
            rm.GetString("Alert_Selecteddataisnotindeletedstatus", ci) + "','" +
            rm.GetString("Alert_Selectdatatorestore", ci) + "','" +
            rm.GetString("Alert_Nodeletedrecordsavailable", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("RestoreAlert", strSetAlert);
        count = 0;
        string gstrUserGroupName = string.Empty;
        gstrUserGroupName = Convert.ToString(Session["UserGroupName"]);
        if (gstrUserGroupName != "SuperAdmin")
        {
            grvLevel.Columns[4].Visible = false;            
            btn_PermanentDelete.Visible = false;
        }
        try
        {
            this.btn_Add.Focus();
            if (!IsPostBack)
            {
                objCommon.menu("OrgSettings", "6");
                Session["parentLevelIdForSearch"] = 0;
                levelid = Convert.ToInt16(Request.QueryString["tid"]);
                if (levelid != 0)
                {
                    Session["orgLevelid"] = levelid;
                    getLevelDetails();
                }
            }
            Cls_CheckUser chck = new Cls_CheckUser();
            DataSet ds = chck.checkRights(6, Convert.ToInt32(Session["userGroup_Id"]), "");
            if (ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["addPrv"] != DBNull.Value && Convert.ToInt32(ds.Tables[0].Rows[0]["addPrv"]) == 1)
                {
                    this.btn_Add.Visible = true;
                }
                else
                {
                    this.btn_Add.Visible = false;
                }
                if (ds.Tables[0].Rows[0]["deletePrv"] != DBNull.Value && Convert.ToInt32(ds.Tables[0].Rows[0]["deletePrv"]) == 1)
                {                    
                    this.grvLevel.Columns[0].Visible = true;
                }
                else
                {
                    this.grvLevel.Columns[0].Visible = false;
                }
            }
            else
            {
                Response.Redirect("MasterLandingPage.aspx");
            }
            if (Session["Demo"] != null && Convert.ToString(Session["Demo"]) == "Express")
            {
                if ((levelid == 1 || Convert.ToInt32(Session["orgLevelid"]) == 1) && Convert.ToInt32(Session["LoadControls"]) > 0)
                {
                    btnDiv.Visible = false;
                    this.btn_Add.Visible = false;
                    btn_Search.Visible = false;
                    btn_Clear.Visible = false;                    
                    this.btn_PermanentDelete.Visible = true;                    
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex);
        }
        if (gintParentId == 0)
        {
            btnDiv.Visible = false;
            btn_Search.Visible = false;
            btn_Clear.Visible = false;
        }
    }
    #endregion
    #region UserDefinedFunctions
    protected void getLevelDetails()
    {
        DataSet dsLev = new DataSet();
        dsLev = selectLevel.selectLevelDetails(Convert.ToInt16(Session["orgLevelid"]), Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["LevelRights"]), Convert.ToInt16(Session["parentLevelId"]));
        if (dsLev.Tables.Count > 0)
        {
            if (dsLev.Tables[0].Rows.Count > 0)
            {
                if ((Convert.ToString(dsLev.Tables[0].Rows[0]["levelName"]) != ""))
                {
                    this.lblHead.Text = Convert.ToString(dsLev.Tables[0].Rows[0]["levelName"]) + " " + rm.GetString("Caption_Details", ci);

                    if (dsLev.Tables[0].Rows[0]["ParentId"] != null && Convert.ToString(dsLev.Tables[0].Rows[0]["ParentId"])!= "")
                    {
                        gintParentId = Convert.ToInt32(dsLev.Tables[0].Rows[0]["ParentId"]);
                    }
                    else
                    {
                        gintParentId = 0;
                    }

                    Session["LoadControls"] = dsLev.Tables[0].Rows.Count;
                }
            }
            else
            {
                gintParentId = 0;
            }
        }
        else
        {
            gintParentId = 0;
        }
    }
    private void FillGrid_Search()
    {
        grvLevel.DataSourceID = "";
        int LevelId = Convert.ToInt32(Request.QueryString["tid"]);
        Session["parentLevelIdForSearch"] = Session["parentLevelId"].ToString();
        int parentLevelId = Convert.ToInt32(Session["parentLevelIdForSearch"]);
        int LeaveIdForSearch = selectLevel.GetLevelId(parentLevelId);
        int PrevLeaveIdCount = selectLevel.getPrevLevelCount(LevelId);
        if (PrevLeaveIdCount != LeaveIdForSearch)
        {
            Session["parentLevelIdForSearch"] = 0;
            grvLevel.DataSourceID = ObjectDataSource2.ID;
            strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_Selectallorganizationlevels", ci) + "')";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("SelectAlert", strScript);
            return;
        }
        grvLevel.DataSourceID = ObjectDataSource2.ID;
    }
    private void LoadStrings(CultureInfo ci)
    {
        String txt = "btn_Add";
        btn_Search.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Search", ci);
        btn_Clear.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Clear", ci);
        btn_Add.Text = "&nbsp;&nbsp;" + rm.GetString(txt, ci);
        btn_cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);        
        btn_PermanentDelete.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Delete", ci);
        grvLevel.Columns[3].Caption = rm.GetString("Designation_DesignationDesc", ci);
        grvLevel.Columns[2].Caption = rm.GetString("LevelDetails_LevelName", ci);
        lblFilter.Text= rm.GetString("lblFilter", ci);
        lblHead2.Text = rm.GetString("lblDataView", ci);
        //grvLevel.Columns[4].Caption = rm.GetString("DeleteStatus", ci);
    }
    private void LoadOrgnaisationLevel()
    {
        cls_master_levels class1 = new cls_master_levels();
        DataSet ds = new DataSet();
        if (Session["UserGroupName"] != null)
        {
            ds = class1.getOrgLevelUpdated(0, Convert.ToString(Session["LevelRights"]), 0, Convert.ToString(Session["UserGroupName"]));
        }
        //stores the organization levels.
        Session["OrgLevels"] = ds;
    }
    public void GetEmptyText(object sender, EventArgs e)
    {
        Label lblNoRecords = (Label)sender;
        lblNoRecords.Text = rm.GetString("Alert_Norecordsfound", ci);
    }
    #endregion
    #region ButtonEvents
    protected void btn_cancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Master_OrganisationLevels.aspx");
    }
    protected void btn_Add_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Master_LevelChildAdd.aspx?tid=" + Request.QueryString["tid"].ToString());
    }
    protected void btn_Search_Click(object sender, EventArgs e)
    {
        //fill gridview based on search details given in textbox
        FillGrid_Search();
    }
    protected void btn_Clear_Click(object sender, EventArgs e)
    {
        Session["parentLevelIdForSearch"] = 0;
        grvLevel.DataSourceID = ObjectDataSource2.ID;
    }
    protected void btn_PermanentDelete_Click(object sender, EventArgs e)
    {
        string[] ChkBoxIDs;
        org_levelsEventData del = new org_levelsEventData();
        LeaveEventData objLeave = new LeaveEventData();
        if (hdnSelectRow.Value != string.Empty && hdnSelectRow.Value != null)
        {
            ChkBoxIDs = objLeave.commaStringToArray(hdnSelectRow.Value);
            for (int i = 0; i < ChkBoxIDs.Length; i++)
            {
                DataSet ds = new DataSet();
                ds = del.CheckForDel(Convert.ToInt32(ChkBoxIDs[i]), "C", "");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0]["checkFlag"] != DBNull.Value)
                    {
                        if (Convert.ToInt16(ds.Tables[0].Rows[0]["checkFlag"]) > 0)
                        {
                            strScript = "";
                            hdnSelectRow.Value = "";
                            strScript = strScript + "<script language='javascript'>";
                            strScript = strScript + "alert('" + rm.GetString("Alert_Cannot_Delete_this_Record_It_is_Already_mapped", ci) + "')";
                            strScript = strScript + "</script>";
                            Page.RegisterStartupScript("DelAlert1", strScript);
                            return;
                        }
                    }
                }
                del.DelLevel(Convert.ToInt32(ChkBoxIDs[i]), "D", "PermanentDelete");
            }
            LoadOrgnaisationLevel();
            strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_Leveldeletedsuccessfully", ci) + "');";
            strScript = strScript + "location.replace('TA_UI_Master_LevelDetails.aspx?tid=" + Session["orgLevelid"] + "&sid=" + Session.SessionID + "');";
            strScript = strScript + "</script>";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
        }
        else
        {
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("DeletionRecordAlert", ci) + "')";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("DelAlert1", strScript);
            return;
        }
    }
    #endregion
    #region GridviewEvents
    protected void grvLevel_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType == GridViewRowType.Data)
        {
            source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            Label DeletedRecord = (Label)grvLevel.FindRowCellTemplateControl(e.VisibleIndex, null, "lblIsDeleted");
          
            if (DeletedRecord != null)
            {
                if (DeletedRecord.Text == "True" || DeletedRecord.Text == rm.GetString("Grid_True", ci))
                {
                    DeletedRecord.ForeColor = System.Drawing.Color.Red;
                }
            }
            org_levelsEventData del = new org_levelsEventData();
            int gid; HtmlInputCheckBox chc; string lbl; DataSet ds = new DataSet();
            chc = (HtmlInputCheckBox)grvLevel.FindRowCellTemplateControl(e.VisibleIndex, null, "chkSelect");
            LinkButton LnkbtnDelete = (LinkButton)grvLevel.FindRowCellTemplateControl(e.VisibleIndex, null, "btnDelete");
            lbl = Convert.ToString(e.GetValue("id"));
            gid = Convert.ToInt32(lbl);
            ds = del.CheckForDel(gid, "C", "");
            if (ds.Tables[0].Rows.Count > 0 && chc != null)
            {
                if (ds.Tables[0].Rows[0]["checkFlag"] != DBNull.Value)
                {
                    if (Convert.ToInt16(ds.Tables[0].Rows[0]["checkFlag"]) > 0)
                    {
                        chc.Disabled = true;
                        LnkbtnDelete.Enabled = false;
                        LnkbtnDelete.OnClientClick = null;
                        count = count + 1;
                    }
                    else
                    {
                        chc.Disabled = false;
                        LnkbtnDelete.Enabled = true;
                    }
                }
            }
            if (DeletedRecord != null)
            {
                if (DeletedRecord.Text == "True")
                {
                    DeletedRecord.Text = rm.GetString("Grid_True", ci);
                    if (hdnDeletedData.Value == string.Empty)
                    {
                        hdnDeletedData.Value = e.GetValue("id").ToString();
                    }
                    else
                    {
                        if (hdnDeletedData.Value.Contains(e.GetValue("id").ToString()) == false)
                        {
                            hdnDeletedData.Value = hdnDeletedData.Value + "," + e.GetValue("id").ToString();
                        }
                    }
                }
                else if (DeletedRecord.Text == "False")
                {
                    DeletedRecord.Text = rm.GetString("Grid_False", ci);
                }
            }
        }
    }
    #endregion
    protected void EditLinkButton_Click(object sender, EventArgs e)
    {
        LinkButton btn = sender as LinkButton;
        int gintLevelID = Convert.ToInt32(btn.CommandName);
        int gintID = Convert.ToInt32(btn.CommandArgument);
        Response.Redirect("TA_UI_Master_LevelChildModify.aspx?tid=" + gintLevelID + " &chID= " + gintID + " &sid=" + Session.SessionID);
    }
    protected void deleteLinkButton_Click(object sender, EventArgs e)
    {
        org_levelsEventData del = new org_levelsEventData();
        int gid;
        LinkButton btn = sender as LinkButton;
        Session["levelid"] = Convert.ToInt32(btn.CommandArgument);
        Session["orgLevelid"] = Convert.ToInt32(btn.CommandName);
        gid = Convert.ToInt16(Session["levelid"]);
        DataSet ds = new DataSet();
        ds = del.CheckForDel(gid, "C", "");
        if (ds.Tables[0].Rows.Count > 0)
        {
            if (ds.Tables[0].Rows[0]["checkFlag"] != DBNull.Value)
            {
                if (Convert.ToInt16(ds.Tables[0].Rows[0]["checkFlag"]) > 0)
                {
                    string strScript = "";
                    strScript = strScript + "<script language='javascript'>";
                    strScript = strScript + "alert('" + rm.GetString("Alert_Cannot_Delete_this_Record_It_is_Already_mapped", ci) + "');history.go(-1)";
                    strScript = strScript + "</script>";
                    Page.RegisterStartupScript("DelAlert1", strScript);
                }
                else
                {
                    del.DelLevel(gid, "D", "PermanentDelete");
                    base.MessageWithRedirect(rm.GetString("Alert_Leveldeletedsuccessfully", ci), "TA_UI_Master_LevelDetails.aspx?tid=" + Session["orgLevelid"] + " &chID= " + Session["levelid"] + " &sid=" + Session.SessionID);
                }
            }
        }
    }

    protected void btnExport_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = (LinkButton)sender;  //Called From  Grid Report Icon click / both excel and pdf
        DisableControls();
        ASPxGridViewExporter1.Landscape = true;
        ASPxGridViewExporter1.LeftMargin = 10;
        ASPxGridViewExporter1.RightMargin = 10;
        ASPxGridViewExporter1.ExportedRowType = DevExpress.Web.GridViewExportedRowType.All;
        ASPxGridViewExporter1.MaxColumnWidth = 400;
        string saveAsFileName = string.Format("Organization Details - {0:d}", DateTime.Now).Replace("/", "-").Replace(" ", "");
        ASPxGridViewExporter1.FileName = saveAsFileName;
        ASPxGridViewExporter1.PaperKind = System.Drawing.Printing.PaperKind.A3;
        switch (lnkbtn.CommandName)
        {
            case "excel":
                ASPxGridViewExporter1.WriteXlsxToResponse();
                break;
            case "pdf":
                ASPxGridViewExporter1.WritePdfToResponse();
                break;
            case "csv":
                ASPxGridViewExporter1.WriteCsvToResponse();
                break;
        }
    }
    private void DisableControls()
    {
        grvLevel.Columns[0].Visible = false;
        grvLevel.Columns[4].Visible = false;
        grvLevel.Columns[5].Visible = false;
        grvLevel.Columns[6].Visible = false;
    }
}
