using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Threading;
using System.Reflection;
using System.Resources;

public partial class Reports_TA_UI_GReport_LatePunctuality : Base.BasePage
{
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    EmployeeEventData objEmployee = new EmployeeEventData();
    DataSet ds_Checkuser = new DataSet();
    HeaderInformation hdrTable = new HeaderInformation();
    GetReports rptEmp = new GetReports();
    Rpt_Common rptcommon = new Rpt_Common();
    ResourceManager rm;
    CultureInfo ci;
    cls_Common objCommon = new cls_Common();
    string strFromdate, gstrDateFormat, strTodate;
    int intIndividualUser = 0;

    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 = Session["Session_ActiveLanguage"].ToString();
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            LoadStrings(ci);
        

        // Set UserRights
        UserRights();

        if (!IsPostBack)
        {
            txtFromDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Session["MDateFormat"].ToString());
            txtToDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Session["MDateFormat"].ToString());

            fillShift();
            BindingEmployeeCategoryandType();
        }


        //Check whether the employee is Individual User

        intIndividualUser = objCheckUser.CheckIndividualUser(Session["UserGroupName"].ToString());

        if (intIndividualUser >= 1)
        {
            PlaceHolderPuntuality.Controls.Clear();
            divEmployeeDetails.Visible = false;
        }

        //Convert date time to MM/dd/YYYY format

        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strFromdate = txtFromDate.Text;
        strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
        strTodate = txtToDate.Text;
        strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
    }

    public void fillShift()
    {
        ShiftEvenData getShift = new ShiftEvenData();
        DataSet ds = new DataSet();
        string strusergroup = string.Empty;
        //ds = getShift.SelectShift(strusergroup, Convert.ToString(Session["LevelRights"]));
        //ds = getShift.SelectShift(Session["UserGroupName"].ToString(), Convert.ToString(Session["LevelRights"]), Convert.ToInt16(Session["parentLevelId"]));
        ds = getShift.SelectShift(Session["UserGroupName"].ToString(), Convert.ToString(Session["LevelRights"]), 0);

        if (ds.Tables[0].Rows.Count > 0)
        {
            this.ddlShift.DataSource = ds;
            this.ddlShift.DataTextField = "Shift_Name";
            this.ddlShift.DataValueField = "Shift_Id";
            this.ddlShift.DataBind();
        }
        ListItem lstItem = new ListItem();
        lstItem.Value = "0";
        lstItem.Text = "All";
        ddlShift.Items.Insert(0, lstItem);

        foreach (ListItem item in ddlShift.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }

    /// <summary>
    /// Bindings the employee category and type.
    /// </summary>
    private void BindingEmployeeCategoryandType()
    {
        // employee category binding
        DataSet dsCategory = new DataSet();
        dsCategory = objEmployee.SelectCategoryDetailsEmployee("");
        if (dsCategory != null)
        {
            if (dsCategory.Tables[0].Rows.Count > 0)
            {
                ddlEmpCatagory.DataSource = dsCategory;
                ddlEmpCatagory.DataTextField = "CategoryName";
                ddlEmpCatagory.DataValueField = "CategoryId";
                ddlEmpCatagory.DataBind();
            }
            dsCategory.Dispose();

            foreach (ListItem item in ddlEmpCatagory.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }

        // employee type binding
        DataSet dsType = new DataSet();
        dsType = objEmployee.SelectTypeDetailsEmployee("");
        if (dsType != null)
        {
            if (dsType.Tables[0].Rows.Count > 0)
            {
                ddlEmpType.DataSource = dsType;
                ddlEmpType.DataTextField = "TypeName";
                ddlEmpType.DataValueField = "TypeId";
                ddlEmpType.DataBind();
            }
            dsType.Dispose();

            foreach (ListItem item in ddlEmpType.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
    }

    /// <summary>
    /// Validate the FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateFromDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            strFromdate = txtFromDate.Text;
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            //strCurrentDate = objCommon.DateConvertion(gstrDateFormat,DateTime.Today.Date.ToString());
            strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
            //strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);

            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date) ;
            DateTime dtFromDate = DateTime.Parse(strFromdate);

            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day <= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch
        {
            //
        }
    }

    /// <summary>
    /// Validate the ToDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateToDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            //strCurrentDate = objCommon.DateConvertion(gstrDateFormat, DateTime.Today.Date.ToString());
            strTodate = txtToDate.Text;
            strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date);
            DateTime dtFromDate = DateTime.Parse(strTodate);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day <= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch
        {
            //
        }
    }

    /// <summary>
    /// Compare ToDate with FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CompareDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            strFromdate = txtFromDate.Text;
            strTodate = txtToDate.Text;
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
            strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);

            DateTime dtToDate = DateTime.Parse(strTodate);
            DateTime dtFromDate = DateTime.Parse(strFromdate);
            TimeSpan diff = dtToDate.Subtract(dtFromDate);
            int day = diff.Days;
            if (day >= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch
        {
            //
        }
    }

    /// <summary>
    /// Load the Punctuality report
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_View_Click(object sender, EventArgs e)
    {
        int intEmployeeCategory = 0, intEmployeeType = 0;
        int employeeCategory = 0, employeeType = 0;
        try
        {
            if (Page.IsValid == true)
            {
                //Create the datatable ,that holds the header information
                DataTable dtHdr = new DataTable();
                dtHdr = hdrTable.CreateHeader();
                dtHdr.TableName = "Header";

                //Add the Header information
                DataRow drHdr = dtHdr.NewRow();
                drHdr["Link"] = 1;
                drHdr["Hdr1"] = "Neuland Laboratories Limited";
                drHdr["Hdr2"] = "NEULAND";
                drHdr["Address1"] = "HeadOffice";
                drHdr["Address2"] = "Hyderabad";
                drHdr["ReportName"] = "Early Exit Report";

                if (txtFromDate.Text != "")
                {
                    DateTime tmpFrom = DateTime.Parse(strFromdate);
                    drHdr["FromDate"] = tmpFrom.ToString("dd-MMM-yyyy");
                }
                else
                    drHdr["FromDate"] = "";
                if (txtToDate.Text != "")
                {
                    DateTime tmpTo = DateTime.Parse(strTodate);
                    drHdr["ToDate"] = tmpTo.ToString("dd-MMM-yyyy");
                }
                else
                    drHdr["ToDate"] = "";

                dtHdr.Rows.Add(drHdr);

                string dtFrom = "", dtTo = "";

                if (txtFromDate.Text != "")
                    dtFrom =strFromdate;

                if (txtToDate.Text != "")
                    dtTo =strTodate;

                // set employee category and type
                //if (ddlEmpCatagory.SelectedItem.ToString() != "-Select-")
                //{
                //    intEmployeeCategory = int.Parse(ddlEmpCatagory.SelectedValue);
                //}
               
                //if (ddlEmpType.SelectedItem.ToString() != "-Select-")
                //{
                //    intEmployeeType = int.Parse(ddlEmpType.SelectedValue);
                //}

                if (Convert.ToInt32(ddlEmpCatagory.SelectedValue) != 0)
                {
                    employeeCategory = Convert.ToInt32(ddlEmpCatagory.SelectedValue);
                }
                else
                {
                    employeeCategory = 0;
                }

                if (Convert.ToInt32(ddlEmpType.SelectedValue) != 0)
                {
                    employeeType = Convert.ToInt32(ddlEmpType.SelectedValue);
                }
                else
                {
                    employeeType = 0;
                }

                int shft = 0;
                string Level = string.Empty;
                string employeeName = string.Empty;
                string empName = string.Empty;
                string empId = string.Empty;

                shft = Convert.ToInt16(this.ddlShift.SelectedValue);

                if (intIndividualUser >= 1)
                {
                    empName = string.Empty;
                    
                    Level = string.Empty;
                    empId = Convert.ToString(Session["EmployeeCodeId"]);
                }
                else
                {

                    empName = txtEmployeeName.Text.ToString();
                    empId = txtEmployeeId.Text.Trim().ToString();
                    employeeName = this.txtEmployeeName.Text.Replace("'", "''");
                    employeeName = employeeName.Replace(' ', '%');

                    if (Convert.ToInt16(Session["parentLevelId"]) != 0)
                    {
                        //Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]));
                        Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));

                    }
                }

                //Get the Report source from the Server and load this into the report table
                DataSet dsPunch = new DataSet();
                
                //this is new report

                dsPunch = rptEmp.Select_Graph_Late_PunctualityReport(empId, Level, dtFrom, dtTo, employeeName, shft, intEmployeeCategory, intEmployeeType, Session["UserGroupName"].ToString(), Convert.ToString(Session["GradeLevel"]), "", Convert.ToInt32(Session["EmpAutoID"]));
                //Report Header
                int orgID = Convert.ToInt16(Session["parentLevelId"]);
                Session["parentLevelId"] = null;
                if (orgID == 0)
                {
                    //orgID = 1;
                    DataSet dsOrgid = new DataSet();
                    dsOrgid = rptEmp.getMinLevel();
                    if (dsOrgid.Tables[0].Rows.Count > 0)
                    {
                        if (dsOrgid.Tables[0].Rows[0]["minID"] != DBNull.Value)
                        {
                            orgID = Convert.ToInt16(dsOrgid.Tables[0].Rows[0]["minID"]);
                        }
                    }
                }
                int lid = 0;
                org_levelsEventData getOrg = new org_levelsEventData();
                getOrg.GetOrgParentLevels_FromID(orgID);
                DataSet ds_getOrg = new DataSet();
                ds_getOrg = getOrg.GetOrgParentLevels();
                if (ds_getOrg.Tables[0].Rows.Count > 0)
                {
                    lid = Convert.ToInt16(ds_getOrg.Tables[0].Rows[0]["levelID"]);
                }
                DataSet dsHeader = new DataSet();
                DataTable dt = new DataTable();
                if (Convert.ToInt16(Session["parentLevelId"]) != 0)
                {
                    dt = rptEmp.getHeader(lid);
                    //if (dsHeader.Tables[0].Rows.Count > 0)
                    //{
                    //    DataTable dtRptHeader = new DataTable();
                    //    dtRptHeader = dsHeader.Tables[0].Copy();
                    //    //dtRptHeader.WriteXmlSchema(@"E:\reportHeader.xml");
                    Session["reportHeader"] = dt;
                    //   }
                }
                else
                {
                    Session["reportHeader"] = dt; 
                }
                //End of Report Header
                Session["parentLevelId"] = null;
                
                DataTable dtEarlyOut = new DataTable();

                //Check the Empty table
                if (dsPunch.Tables["Table"] == null || dsPunch.Tables["Table"].Rows.Count == 0)
                {
                    string strMsg;
                    strMsg = "<script language='javascript'>";
                    //strMsg = strMsg + "alert('There is no record ');";
                    strMsg = strMsg + "alert('" + rm.GetString("Alert_Thereisnorecord", ci) + "');";
                    strMsg = strMsg + "</script>";
                    
                    Page.RegisterStartupScript("Display Message", strMsg);

                    return;
                }

                dtEarlyOut = dsPunch.Tables["Table"].Copy();

                //Add the link column
                DataColumn dcLink = new DataColumn("Link", Type.GetType("System.Int32"));
                dtEarlyOut.Columns.Add(dcLink);

                for (int i = 0; i < dtEarlyOut.Rows.Count; i++)
                {
                    dtEarlyOut.Rows[i]["Link"] = 1;
                }

                //WRITE XML SCHEMA TO DISK - THIS IS ONLY REQUIRED DURING DEVELOPMENT TO BUILD THE REPORT
                //dtEarlyOut.WriteXmlSchema(@"E:\G_Late_Punctuality.xml");
                //dtHdr.WriteXmlSchema(@"E:\G_Late_PunctualityHdr.xml");
                //return;

                //Set the session variable that holds the report table and report header table
                Session["Hdr"] = dtHdr;
                Session["Source"] = dtEarlyOut;
                //Session["Path"] = Server.MapPath(rm.GetString("rptPunctuality",ci));

                Session["Path"] = Server.MapPath("LatePunctualityGraph.rpt");

                //Redirect the page to the report viewer
                string strScript = "";
                string strUrl = "TA_UI_Report_ReportViewer.aspx";
                strScript = "<script language='javascript'>";
                strScript = strScript + "window.open('" + strUrl + "');";
                strScript = strScript + "</script>";
              Response.Write(strScript);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex);
            //
        }
    }

    //Getting Information from resource file and display it in label

    private void LoadStrings(CultureInfo ci)
    {
        btn_View.Text = rm.GetString("btn_View", ci);
        ddlEmpCatagory.Items[0].Text = rm.GetString("Select", ci);
        ddlEmpType.Items[0].Text = rm.GetString("Select", ci);
    }

    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(39, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");

        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)
            {
                btn_View.Visible = true;
            }
            else
            {
                btn_View.Visible = false;
            }
        }
        else
        {
            Response.Redirect("ReportsLandingPage.aspx");
        }
    }

}
