using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
/****************************************************************************************************************************
* Project Name    : TimeCheck                                        Started Date  : 12-Aug-2007
* Module          : Terminal Master                                  Last Modified : 14-Aug-2007
* Programmer      : 
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          :
****************************************************************************************************************************/
public partial class Masters_TA_UI_Master_ProjectAdd : Base.BasePage
{
    #region VariableDeclaration
    ResourceManager rm;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    cls_Common objCommon = new cls_Common();
    DataSet ds_Checkuser = new DataSet();
    CultureInfo ci;
    ProjectEventData objProjectEventData = new ProjectEventData();
    string strSetAlert;
    string Project_Id = "0";
    int EmployeeID, intRawDataFormat = 0;
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        txtProjectId.Focus();
        string source_Language;
        //Need to explain to her
        string gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        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"]);
        EmployeeID = Convert.ToInt32(Session["EmpAutoID"]);
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
        if (Request.QueryString["Project_Id"] != null && Convert.ToString(Request.QueryString["Project_Id"]) != "")
        {
            Project_Id = Convert.ToString(Request.QueryString["Project_Id"]);
        }
        if (!IsPostBack)
        {
            LoadStrings(ci);
            UserRights();
            base.CheckPages(283);
            objCommon.menu("Configuration", "283");
            btn_save.OnClientClick = "if(Page_ClientValidate()) return confirm('" + rm.GetString("Alert_ConfirmSave", ci) + "');return false;";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("MaxLengthh", strSetAlert);
            if (Project_Id != "0")
            {
                LoadProjectDetails(Project_Id);
                divAddOrganization.Style.Add("display", "none");
                divModifyOrganization.Style.Add("display", "");
            }
            else
            {
                divAddOrganization.Style.Add("display", "");
                divModifyOrganization.Style.Add("display", "none");
                Session["parentLevelId"] = "0";
                Session["parentLevelId_modify"] = "0";
                DataTable dt = new DataTable();
                dt.Columns.Add("TaskID", typeof(string));
                dt.Columns.Add("TaskName", typeof(string));
                dt.Columns.Add("Hours", typeof(string));
                dt.TableName = "TaskDetails";
                ViewState["TaskDetails"] = dt;
                BindData();
            }
        }

    }

    #endregion
    #region ButtonEvents
    protected void btn_cancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Master_ProjectList.aspx");
    }
    protected void btn_save_Click(object sender, EventArgs e)
    {
        string strGender = string.Empty, strScript = string.Empty, gstrDateFormat = "";
        string Project_Name = string.Empty, Project_Code = string.Empty, Client_Name = string.Empty, ContactNumber = string.Empty, Project_Description = string.Empty, Project_Status = string.Empty, NoOfTerminals = string.Empty, Project_StartTime = string.Empty, Project_EndTime = string.Empty;
        string strTerminals = string.Empty;
        int intLoop, count = 0, SelectedTerminalsCount = 0;
        string strScript1 = "", Datetimevalidation = "1";
        DataSet CheckTerminalsisinUse = new DataSet();
        string ProjectInProgressName = string.Empty;
        if (Page.IsValid)
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);

            //reading values from pages
            if (Convert.ToString(txtProjectName.Text) != "")
            {
                Project_Name = Convert.ToString(txtProjectName.Text);
            }
            if (Convert.ToString(txtProjectId.Text) != "") { Project_Code = txtProjectId.Text; }
            if (Convert.ToString(txtClientName.Text) != "") { Client_Name = txtClientName.Text; }
            if (Convert.ToString(txtProjectDescription) != "") { Project_Description = txtProjectDescription.Text; }

            Project_Status = ddlProjectStatus.SelectedValue;
            if (Project_Status == "-Select-")
            {
                Project_Status = "In Progress"; //in default we save project in In Progress State as per SRS
            }


            if (Project_Id == "0")
            {
                count = objProjectEventData.Check_duplicateProject(Project_Name);
                if (count > 0)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Project_DuplicateProjectName", ci) + "');", true);
                    return;
                }
            }
            Project_StartTime = objCommon.DateConvertion(gstrDateFormat, txtProjectStartDate.Text.Trim());
            Project_EndTime = objCommon.DateConvertion(gstrDateFormat, txtProjectEndDate.Text.Trim());
            if (Project_StartTime != "" && Project_EndTime != "")
            {
                Datetimevalidation = (Convert.ToDateTime(Project_EndTime).Date >= Convert.ToDateTime(Project_StartTime).Date) ? "1" : "0";
                if (Datetimevalidation == "0") //check Satrt time end time
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Project_DatecompareAlert", ci) + "');", true);
                    return;
                }
            }
            int intLevelID = 0;
            if ((Session["parentLevelId"]) != null)
            {
                intLevelID = Convert.ToInt32(Session["parentLevelId"]);
            }
            //if (intLevelID == 0) //check Satrt time end time
            //{
            //    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_SelectOrganizationlevel1", ci) + "');", true);
            //    return;
            //}
            DataTable dtTable = (DataTable)ViewState["TaskDetails"];
            if (Convert.ToInt32(dtTable.Rows.Count) == 0)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_SelectTask_Details", ci) + "');", true);
                return;
            }
            if (count == 0 && Datetimevalidation == "1")
            {
                StringWriter strWriteXML = new StringWriter();
                DataSet ds = new DataSet();
                ds.Tables.Add(dtTable);
                ds.WriteXml(strWriteXML);
                string strDataXML = Convert.ToString(strWriteXML);
                objProjectEventData.InsertUpdateProjectDetails
                    (
                        Project_Id,
                        Project_Name,
                        Project_Code,
                        Client_Name,
                        Project_Description,
                        Project_Status,
                        Project_StartTime,
                        Project_EndTime,
                        Convert.ToInt32(Session["EmpAutoID"]),
                        Convert.ToString(intLevelID),
                        Convert.ToString(txtMandays.Text),
                        Convert.ToString(txtManHours.Text),
                        strDataXML
                     );
                if (Project_Id == "0")
                {
                    strScript1 = "alert('" + rm.GetString("Project_AlertSavedSuccessfully", ci) + "');location.replace('TA_UI_Master_ProjectList.aspx')";
                }
                else
                {
                    strScript1 = "alert('" + rm.GetString("Project_AlertModifiedSuccessfully", ci) + "');location.replace('TA_UI_Master_ProjectList.aspx')";
                }
                Page.ClientScript.RegisterStartupScript(this.GetType(), "alertBox", strScript1, true);
            }
        }
    }
    #endregion
    #region UserDefinedFunctions
    private void LoadStrings(CultureInfo ci)
    {
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lbl_ProjectId.Text = rm.GetString("Project_ProjectCode", ci);
        lbl_ProjectName.Text = rm.GetString("Project_Name", ci);
        lbl_ProjectStartdate.Text = rm.GetString("Project_Startdate", ci);
        lbl_ProjectEndDate.Text = rm.GetString("Project_Enddate", ci);
        lbl_ClientName.Text = rm.GetString("Project_ClientName", ci);
        lbl_ProjectDescription.Text = rm.GetString("Project_Description", ci);
        lbl_Status.Text = rm.GetString("Project_Status", ci);
        lbl_ProjectMaster.Text = rm.GetString("Project_AddPage", ci);
        btn_save.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btn_cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(283, Convert.ToInt32(Session["userGroup_Id"]), "addPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("MasterLandingPage.aspx");
        }
    }
    public void CheckOutDate(object s, ServerValidateEventArgs e)
    {
        string strOutDate = "";
        string gstrDateFormat;
        if (txtProjectEndDate.Text != "")
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strOutDate = objCommon.DateConvertion(gstrDateFormat, txtProjectEndDate.Text);
            DateTime dtCurrent = DateTime.Now;
            DateTime dtOutDate = DateTime.Parse(strOutDate);
            int Days = dtCurrent.CompareTo(dtOutDate);
            if (Days > 0)
            {
                e.IsValid = true;
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Validator_ManualTimeEntry_OutDate", ci) + "');", true);
                txtProjectEndDate.Focus();
                e.IsValid = false;
            }
        }
        else
        {
            e.IsValid = true;
        }

    }
    public void LoadProjectDetails(string ProjectId)
    {
        DataSet dsProject = new DataSet();
        dsProject = objProjectEventData.ViewProjectbyProjectId(Convert.ToInt32(ProjectId), Convert.ToInt32(Session["EmpAutoID"]));
        if (dsProject != null)
        {
            if (dsProject.Tables[0].Rows.Count > 0)
            {
                txtProjectName.Text = dsProject.Tables[0].Rows[0]["Project_Name"].ToString();
                txtProjectId.Text = dsProject.Tables[0].Rows[0]["Project_Code"].ToString();
                txtClientName.Text = dsProject.Tables[0].Rows[0]["Client_Name"].ToString();
                txtProjectDescription.Text = dsProject.Tables[0].Rows[0]["Project_Description"].ToString();
                //ddlTerminals.SelectedValue = dsProject.Tables[0].Rows[0]["NoOfTerminals"].ToString();
                ddlProjectStatus.SelectedValue = dsProject.Tables[0].Rows[0]["Project_Status"].ToString();
                txtProjectStartDate.Text = dsProject.Tables[0].Rows[0]["Project_StartTime"].ToString();
                txtProjectEndDate.Text = dsProject.Tables[0].Rows[0]["Project_EndTime"].ToString();
                txtManHours.Text = dsProject.Tables[0].Rows[0]["ManHours"].ToString();
                txtMandays.Text = dsProject.Tables[0].Rows[0]["Mandays"].ToString();
                Session["parentLevelId"] = dsProject.Tables[0].Rows[0]["LevelID"].ToString();
                Session["parentLevelId_modify"] = dsProject.Tables[0].Rows[0]["LevelID"].ToString();
                //GenerateHtmlTableForTerminals(Convert.ToInt16(ddlTerminals.SelectedValue));
                //FillTerminalValues(Convert.ToInt16(ddlTerminals.SelectedValue));
            }
            if (dsProject.Tables[1].Rows.Count > 0)
            {
                DataTable dt = new DataTable();
                dt = dsProject.Tables[1].Copy();
                dt.TableName = "TaskDetails";
                foreach (DataRow Drow in dt.Rows)
                {
                    if (Drow["TaskName"] == DBNull.Value)
                    {
                        dt.Rows.Remove(Drow);
                        break;
                    }
                }
                dt.AcceptChanges();
                ViewState["TaskDetails"] = dt;
                BindData();
            }
        }

    }
    #endregion

    protected void gvTask_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("ADD"))
        {
            TextBox txtReminder = (TextBox)gvTask.FooterRow.FindControl("txtAdd_TaskName");
            TextBox txtHours = (TextBox)gvTask.FooterRow.FindControl("txtAdd_Hours");
            string strScript = "";
            if (txtReminder != null && txtHours != null)
            {
                string TaksName = "", TaskHours = "";
                if (Convert.ToString(txtReminder.Text) != "")
                {
                    TaksName = Convert.ToString(txtReminder.Text);
                }
                if (Convert.ToString(txtHours.Text) != "")
                {
                    TaskHours = Convert.ToString(txtHours.Text);
                }
                InsertTaskDetails(Convert.ToString(TaksName), Convert.ToString(TaskHours));

                ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", strScript, true);

            }
            BindData();
        }
    }
    protected void BindData()
    {
        DataTable dtTable = (DataTable)ViewState["TaskDetails"];
        if (dtTable.Rows.Count > 0)
        {
            gvTask.DataSource = dtTable;
            gvTask.DataBind();
        }
        else
        {
            dtTable.Rows.Add(dtTable.NewRow());
            gvTask.DataSource = dtTable;
            gvTask.DataBind();
            gvTask.Rows[0].Cells[0].Text = "No records Found";
            gvTask.Rows[0].Visible = false;
        }
    }

    protected void InsertTaskDetails(string TaskName, string TaskHours)
    {
        DataTable dtTable = (DataTable)ViewState["TaskDetails"];
        DataRow DR = dtTable.NewRow();
        int tblCount = 0;
        foreach (DataRow Drow in dtTable.Rows)
        {
            if (Drow["TaskID"] == DBNull.Value)
            {
                dtTable.Rows.Remove(Drow);
                break;
            }
        }
        dtTable.AcceptChanges();
        if (dtTable.Rows.Count > 0)
        {
            int rowCount = 0, intval = 0;
            rowCount = dtTable.Rows.Count - 1;
            intval = Convert.ToInt32(dtTable.Rows[rowCount]["TaskID"]);
            tblCount = intval + 1;
        }
        else
        {
            tblCount = 1;
        }

        DR["TaskID"] = Convert.ToString(tblCount);
        DR["TaskName"] = TaskName;
        DR["Hours"] = TaskHours;
        dtTable.Rows.Add(DR);
    }


    protected void gvTask_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Label lblMatrixId = (Label)gvTask.Rows[e.RowIndex].FindControl("lblTaskId");
        if (lblMatrixId != null)
        {
            DeleteTaskDetails(Convert.ToInt32(lblMatrixId.Text));
        }
        BindData();
    }
    protected void DeleteTaskDetails(Int32 TaskID)
    {
        try
        {
            DataTable dtTable = (DataTable)ViewState["TaskDetails"];
            foreach (DataRow DR in dtTable.Rows)
            {
                if (Convert.ToInt32(DR["TaskID"]) == TaskID)
                {
                    DR.Delete();
                    break;
                }
            }
            dtTable.AcceptChanges();
        }
        catch (Exception)
        {

            throw;
        }
    }
    protected void UpdateTaskDetails(Int32 TaskID, string TaskName, string TaskHours)
    {
        DataTable dtTable = (DataTable)ViewState["TaskDetails"];
        foreach (DataRow DR in dtTable.Rows)
        {
            if (Convert.ToInt32(DR["TaskID"]) == TaskID)
            {
                DR["TaskName"] = TaskName;
                DR["Hours"] = TaskHours;
            }
        }
        dtTable.AcceptChanges();

    }


    protected void gvTask_RowDataBound(object sender, GridViewRowEventArgs e)
    {

    }
    protected void gvTask_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        TextBox txtTaskName = (TextBox)gvTask.Rows[e.RowIndex].FindControl("txtedit_TaskName");
        TextBox txtHours = (TextBox)gvTask.Rows[e.RowIndex].FindControl("txtedit_Hours");
        Label lblTaskId = (Label)gvTask.Rows[e.RowIndex].FindControl("lblTaskId");
        if (lblTaskId != null && txtTaskName != null && txtHours != null)
        {
            string TaskName = "", TaskHours = "";
            if (Convert.ToString(txtTaskName.Text) != "")
            {
                TaskName = Convert.ToString(txtTaskName.Text);
            }
            if (Convert.ToString(txtHours.Text) != "")
            {
                TaskHours = Convert.ToString(txtHours.Text);
            }
            UpdateTaskDetails(Convert.ToInt32(lblTaskId.Text), TaskName, TaskHours);
        }
        gvTask.EditIndex = -1;
        BindData();
    }

    protected void gvTask_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvTask.EditIndex = -1;
        BindData();
    }
    protected void gvTask_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvTask.EditIndex = e.NewEditIndex;
        BindData();
    }
}
