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;
using System.Text.RegularExpressions;
using System.IO;
/****************************************************************************************************************************
* Project Name    : TimeCheck                                   Started Date  : 12-Aug-2007
* Module          : Temporary WeekDay Settings                  Last Modified : 14-Aug-2007
* Programmer      : Janakaraj.P
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
****************************************************************************************************************************/
public partial class Organization_Settings_Organization_TemporaryWeekday : Base.BasePage
{
    #region Global Variable Declaration
    ResourceManager rm;
    CultureInfo ci;
    userRightsEventData objClass = new userRightsEventData();
    TempWeekdayEvendata obj = new TempWeekdayEvendata();
    cls_Common objcls_Common = new cls_Common();
    string gstrDateFormat;
    int gintHolidayCount = 0;
    string strFromdate, strTodate;
    int TempWeekId = 0;
    DataSet ds = new DataSet();
    #endregion

    #region Page Load Events
    protected override void Page_Load(object sender, EventArgs e)
    {
        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"]);
        if (source_Language == "Resources.Resource_AR")
        {
            tvLevel.LineImagesFolder = "../dist/img/TreeLineImage_RTL";
        }
        
        LoadStrings(ci);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_FillWeekdayFromDate", ci) + "','" + rm.GetString("Alert_FillWeekdayToDate", ci) + "','" + rm.GetString("Alert_FillClosingTime", ci) + "','" + rm.GetString("Alert_FillReasons", ci) + "','" + rm.GetString("Alert_Are_you_sure_to_Save", ci) + "','" + rm.GetString("Alert_SelectShift_TempWeekDay", ci) + "','" + rm.GetString("Alert_NotValidShiftForLevels_TempWeekDay", ci) + "','" + rm.GetString("Alert_ClickLoadShift", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertCheckDate('" + rm.GetString("Alert_Validmonthdatefourdigit", ci) + "','" + rm.GetString("Alert_Validdatemonthfourdigit", ci) + "','" + rm.GetString("Alert_Invalidyearentry", ci) + "','" + rm.GetString("Alert_Invalidmonthentry", ci) + "','" + rm.GetString("Alert_Invaliddateentry", ci) + "','" + rm.GetString("Alert_IncorrectdateformatDDMONYYYY", ci) + "','" + rm.GetString("Alert_Entertime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "','" + rm.GetString("Alert_Invalidtimeformat1", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMM", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMMTT", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        if (!IsPostBack)
        {
            if (Request.QueryString["TempWeekDayId"] != null)
            {
                TempWeekId = Convert.ToInt32(Request.QueryString["TempWeekDayId"].ToString());
                getShiftByWeekDayId(TempWeekId);
           } 
            getNodes();
            Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
            Hidden2.Value = Convert.ToString(Session["ITimeFormat"]);
            //Todo: need to update this line into updated one.
            //txtWeekFromDate.Focus();
            if (TempWeekId != 0)
            {
                btn_Save.Visible = false;
            }
        }
    }
    #endregion

    #region User Defined Functions
    public void getShiftByWeekDayId(int Id)
    {
        getNodes();
        LoadShift();
        DataSet ds = obj.GetShiftByWeekDayId(Id);
        if (ds != null)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    ListItem thisIndex = cklstShift.Items.FindByValue(Convert.ToString(ds.Tables[0].Rows[i]["ShiftId"]));
                    if (thisIndex != null)
                        thisIndex.Selected = true;
                }
                if (ds.Tables[0].Rows.Count == cklstShift.Items.Count)
                {
                    cbAll.Checked = true;
                }
            }
        }
    }
    private void LoadStrings(CultureInfo ci)
    {
        lblMandatory.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lbl_Header.Text = rm.GetString("OrganizationSettings_TemporaryWeekDay_TemporaryWeekDaySetting", ci);
        lblShift.Text = rm.GetString("Menu_Reports_Shift", ci);
        lbl_TempWeekFromDate.Text = rm.GetString("Reports_Date", ci);
        lbl_TempWeekToDate.Text = rm.GetString("OnDuty_OutDate", ci);
        lbl_Reason.Text = rm.GetString("email_Reason", ci);
        lbl_ClosingTime.Text = rm.GetString("TemporaryWeekDaySetting_ClosingTime", ci);
        btn_Save.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        cus_ComDate.ErrorMessage = rm.GetString("Msg_GrearterThanFrmDate", ci);
        lblLoading.Text = rm.GetString("ProgressBarText", ci);
        btnLoadShift.Text = "&nbsp;&nbsp;" + rm.GetString("lbl_LoadShift", ci);
    }
    public void LoadShift()
    {
        string strAlert = "";
        hdfLoadShift.Value = "1";
        cklstShift.DataSource = null;
        cbAll.Checked = false;
        string strLevelIdShift = "";
        TreeNodeCollection collection = tvLevel.CheckedNodes;
        if (collection.Count > 0)
        {
            TreeNode[] trc = new TreeNode[collection.Count];
            collection.CopyTo(trc, 0);
            foreach (TreeNode tr in trc)
            {
                if (strLevelIdShift == string.Empty)
                    strLevelIdShift = tr.Value;
                else
                    strLevelIdShift = strLevelIdShift + "," + tr.Value;
            }
            DataSet ds = obj.LoadShiftByLevels(strLevelIdShift);
            if (ds.Tables[0].Rows.Count > 0)
            {
                DataView view = new DataView();
                view = ds.Tables[0].DefaultView;
                string strDate = "1900-01-01";
                DateTime dttClosingTime = DateTime.Parse(strDate + " " + txt_closingtime.Text.Trim());
                int Hour = (dttClosingTime.Hour % 12) + 12;
                if (txt_closingtime.Text.Trim().Contains("AM"))
                {
                    strDate = "1900-01-02";
                    dttClosingTime = dttClosingTime.AddDays(1);
                }
                //else if (Hour >= 12 && Hour <= 18)
                //{

                //}
                view.RowFilter = "Shift_StartTime<= '" + dttClosingTime + "' and Shift_EndTime>='" + dttClosingTime + "'";
                DataTable dtTemp = view.ToTable();
                if (dtTemp.Rows.Count > 0)
                {
                    cklstShift.DataSource = dtTemp;
                    cklstShift.DataValueField = "Shift_Id";
                    cklstShift.DataTextField = "Shift_ShortName";
                    cklstShift.DataBind();
                    trShiftLoad.Attributes.Add("style", "display:''");
                }
                else
                {
                    cklstShift.Items.Clear();
                    cklstShift.DataSource = null;
                    cklstShift.DataBind();
                    trShiftLoad.Attributes.Add("style", "display:none");
                    strAlert = rm.GetString("Alert_NoShiftForThsClosingTime_TempWeekday", ci);
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + strAlert + "');", true);
                    txt_closingtime.Focus();
                    return;
                }
            }
            else
            {
                cklstShift.Items.Clear();
                cklstShift.DataSource = null;
                cklstShift.DataBind();
                trShiftLoad.Attributes.Add("style", "display:none");
                strAlert = rm.GetString("Alert_NotValidShiftForLevels_TempWeekDay", ci);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + strAlert + "');", true);
                return;
            }
        }
        else
        {
            cklstShift.Items.Clear();
            cklstShift.DataSource = null;
            cklstShift.DataBind();
            trShiftLoad.Attributes.Add("style", "display:none");
            strAlert = rm.GetString("Alert_SelectLevels_TempWeekday", ci);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + strAlert + "');", true);
            tvLevel.Focus();
            return;
        }
    }
    public void getNodes()
    {
        try
        {
            DataSet ds = new DataSet();
            tvLevel.Nodes.Clear();
            ds = obj.GetTemporaryWeekdayLevels(TempWeekId);
            string strLevelID = "";
            if (ds != null)
            {
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        txtWeekFromDate.Text = ds.Tables[0].Rows[0][0].ToString();
                        txtWeekToDate.Text = ds.Tables[0].Rows[0][1].ToString();
                        txt_closingtime.Text = ds.Tables[0].Rows[0][2].ToString();
                        txt_Reason.Text = ds.Tables[0].Rows[0][3].ToString();
                        if (ds.Tables[0].Rows[0][4] != DBNull.Value)
                        {
                            strLevelID = Convert.ToString(ds.Tables[0].Rows[0][4]);

                        }
                    }
                }
            }
            string str = strLevelID;
            char[] comma ={ ',' };
            string[] str1 = str.Split(comma);
            GetReports levl = new GetReports();
            DataSet dsLev = new DataSet();
            dsLev = levl.SelectLevelDetails();
            int count;
            for (count = 0; count <= dsLev.Tables[0].Rows.Count - 1; count++)
            {
                TreeNode root = new TreeNode();
                if (Convert.ToInt16(dsLev.Tables[0].Rows[count]["parentid"]) == 0)
                {
                    DropDownList dd = new DropDownList();
                    dd.DataTextField = Convert.ToString(dsLev.Tables[0].Rows[count]["Name"]);
                    dd.DataBind();
                    root.Text = Convert.ToString(dsLev.Tables[0].Rows[count]["Name"]);
                    root.Value = Convert.ToString(dsLev.Tables[0].Rows[count]["id"]);
                    root.Expanded = true;
                    root.SelectAction = TreeNodeSelectAction.SelectExpand;
                    getChildNodes(root, Convert.ToInt16(dsLev.Tables[0].Rows[count]["id"]), strLevelID);
                    if (TempWeekId != 0)
                    {
                        foreach (DataRow drLevel in ds.Tables[0].Rows)
                        {
                            if (drLevel["LevelId"].ToString() == root.Value)
                            {
                                root.Checked = true;
                            }
                        }
                    }
                    root.Target = "FrameCon"; // or any other target
                    this.tvLevel.Nodes.Add(root);
                }
            }
            dsLev.Dispose();
        }
        catch (Exception ex)
        {
            Response.Write(ex);
        }
    }
    public void getChildNodes(TreeNode parent, Int16 menuNo, string strLevelID)
    {
        DataSet ds = new DataSet();
        ds = obj.GetTemporaryWeekdayLevels(TempWeekId);
        string strLevelID1 = String.Empty;
        if (ds != null)
        {
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {

                    if (ds.Tables[0].Rows[0]["LevelId"] != DBNull.Value)
                    {
                        strLevelID1 = Convert.ToString(ds.Tables[0].Rows[0]["LevelId"]);
                    }
                    string str = strLevelID1;
                    char[] comma ={ ',' };
                    string[] str1 = str.Split(comma);
                }
            }
        }
        GetReports levl = new GetReports();
        DataSet dsLev1 = new DataSet();
        dsLev1 = levl.SelectLevelDetails();
        TreeNode childNode;
        int rowCount = 0, kloop = 0;
        for (kloop = 0; kloop <= dsLev1.Tables[0].Rows.Count - 1; kloop++)
        {
            if (Convert.ToInt16(dsLev1.Tables[0].Rows[kloop]["parentId"]) == menuNo)
            {
                rowCount += 1;
            }
        }
        if (rowCount != 0)
        {
            for (kloop = 0; kloop <= dsLev1.Tables[0].Rows.Count - 1; kloop++)
            {
                if (Convert.ToInt16(dsLev1.Tables[0].Rows[kloop]["parentId"]) == menuNo)
                {
                    childNode = new TreeNode();
                    childNode.Text = Convert.ToString(dsLev1.Tables[0].Rows[kloop]["Name"]);
                    childNode.Value = Convert.ToString(dsLev1.Tables[0].Rows[kloop]["Id"]);
                    childNode.Expanded = true;
                    childNode.SelectAction = TreeNodeSelectAction.SelectExpand;
                    if (TempWeekId != 0)
                    {
                        foreach (DataRow drLevel in ds.Tables[0].Rows)
                        {
                            if (drLevel["LevelId"].ToString() == childNode.Value)
                            {
                                childNode.Checked = true;
                            }
                        }
                    }
                    childNode.Target = "FrameCon"; // or any other target
                    parent.ChildNodes.Add(childNode);
                    getChildNodes(childNode, Convert.ToInt16(dsLev1.Tables[0].Rows[kloop]["id"]), strLevelID1);
                }
            }
        }
        dsLev1.Dispose();
    }
    public void CompareDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            strFromdate = txtWeekFromDate.Text;
            strTodate = txtWeekFromDate.Text;
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strTodate = objcls_Common.DateConvertion(gstrDateFormat, strTodate);
            strFromdate = objcls_Common.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
        {
        }
    }
    public string getSelectedShift()
    {
        string ShiftId = "";
        if (cklstShift != null)
        {
            if (cklstShift.Items.Count > 0)
            {
                for (int i = 0; i < cklstShift.Items.Count; i++)
                {
                    if (cklstShift.Items[i].Selected == true)
                    {
                        if (ShiftId == string.Empty)
                            ShiftId = cklstShift.Items[i].Value;
                        else
                            ShiftId = ShiftId + "," + cklstShift.Items[i].Value;
                    }
                }
            }
        }
        return ShiftId;
    }
    #endregion

    #region Button Click Events
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        string strAlert = "";
        string strShiftId = "";
        //Added by Manjula.P on 11-Aug-2014 for checking global holiday weekday : Bug No :0025313
        string strLevelIdValue = string.Empty;
        StringWriter strLevelId = new StringWriter();
        if (Page.IsValid == true)
        {
            try
            {
                TreeNodeCollection collection = tvLevel.CheckedNodes;
                if (collection.Count > 0)
                {
                    TreeNode[] trc = new TreeNode[collection.Count];
                    collection.CopyTo(trc, 0);
                    DataTable dtTempWeekday = new DataTable("Ta_Tbl_Temporary_WeeklyOff_Levels");
                    DataColumn dcTempWeekId = new DataColumn("LevelId", System.Type.GetType("System.Int32"));
                    dtTempWeekday.Columns.Add(dcTempWeekId);
                    DataRow drNew;
                    foreach (TreeNode tr in trc)
                    {
                        drNew = dtTempWeekday.NewRow();
                        drNew.BeginEdit();
                        drNew["LevelId"] = tr.Value;
                        drNew.EndEdit();
                        dtTempWeekday.Rows.Add(drNew);
                        //Added by Manjula.P on 11-Aug-2014 for checking global holiday weekday : Bug No :0025313
                        if (strLevelIdValue == string.Empty)
                            strLevelIdValue = tr.Value;
                        else
                            strLevelIdValue = strLevelIdValue + "," + tr.Value;
                    }
                    if (dtTempWeekday.Rows.Count > 0)
                    {
                        dtTempWeekday.WriteXml(strLevelId);
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_Organizationdetailscannotbeempty", ci) + "');", true);
                    return;
                }
                strShiftId = getSelectedShift();
                int UserId, count;
                UserId = Convert.ToInt32(Session["EmpAutoID"]);
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                string strWeekDate = "";
                strWeekDate = objcls_Common.DateConvertion(gstrDateFormat, txtWeekFromDate.Text);
                string strWeekToDate = "";
                strWeekToDate = objcls_Common.DateConvertion(gstrDateFormat, txtWeekFromDate.Text);
                DataSet ds_Year = new DataSet();
                DateTime dtmFromDate = new DateTime();
                DateTime dtmToDate = new DateTime();
                ds_Year = objcls_Common.GetYearsetting();
                if (ds_Year != null)
                {
                    if (ds_Year.Tables[0].Rows.Count > 0)
                    {
                        if (ds_Year.Tables[0].Rows[0]["FromDate"] != DBNull.Value)
                        {
                            dtmFromDate = DateTime.Parse(ds_Year.Tables[0].Rows[0]["FromDate"].ToString());
                        }
                        if (ds_Year.Tables[0].Rows[0]["ToDate"] != DBNull.Value)
                        {
                            dtmToDate = DateTime.Parse(ds_Year.Tables[0].Rows[0]["ToDate"].ToString());
                        }
                    }
                }
                DateTime dtmCurrentDate = DateTime.Now.Date;
                DateTime dtmWeekDate = Convert.ToDateTime(strWeekDate);
                DateTime dtmWeekToDate = Convert.ToDateTime(strWeekToDate);
                if ((dtmFromDate <= dtmWeekDate) && (dtmWeekDate <= dtmToDate) && ((dtmFromDate <= dtmWeekToDate) && (dtmWeekToDate <= dtmToDate)))
                {
                }
                else
                {
                    strAlert = rm.GetString("TemporaryWeekDaySetting_ActiveYear", ci);
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("TemporaryWeekDaySetting_ActiveYear", ci) + "');", true);
                    txtWeekFromDate.Focus();
                    return;
                }
                gintHolidayCount = obj.CheckTempWeekDayHoliday_Insert(0, strWeekDate, strWeekToDate, "I", strLevelIdValue);
                if (gintHolidayCount > 0)
                {
                    strAlert = rm.GetString("TemporaryWeekDaySetting_HolidayExists", ci);
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("TemporaryWeekDaySetting_HolidayExists", ci) + "');", true);
                    return;
                }
                count = obj.CheckTempWeekDay_Insert(strWeekDate, strWeekToDate, strLevelId.ToString(), txt_closingtime.Text.Trim(), strShiftId);
                if (count == 0)
                {
                    if (TempWeekId != 0)
                    {
                        ds = obj.InsertWeekday(strWeekDate, strWeekToDate, Convert.ToDateTime(txt_closingtime.Text).ToString("hh:mm tt"), txt_Reason.Text.Replace("'", "''"), UserId, strLevelId.ToString(), TempWeekId, strShiftId);
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            if (ds.Tables[0].Rows[0][0].ToString() == "updated")
                            {
                                string str = "alert('" + rm.GetString("Alert_SelectedTemporaryWeekDaymodifiedSuccessfully", ci) + "');location.replace('Organization_Tempweekdaylist.aspx?');";
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", str, true);
                            }
                            else
                            {
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_TemporaryWeekDaycannotbeModified", ci) + "');", true);
                                return;
                            }
                        }
                    }
                    else
                    {
                        ds = obj.InsertWeekday(strWeekDate, strWeekToDate, Convert.ToDateTime(txt_closingtime.Text).ToString("hh:mm tt"), txt_Reason.Text.Replace("'", "''"), UserId, strLevelId.ToString(), 0, strShiftId);
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            if (ds.Tables[0].Rows[0][0].ToString() == "1")
                            {
                                string str = "alert('" + rm.GetString("Alert_TemporaryWeekdaySavedSuccessfully", ci) + "');location.replace('Organization_Tempweekdaylist.aspx?');";
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", str, true);
                            }
                            else
                            {
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_TemporaryWeekDaycannotbeadded", ci) + "');", true);
                                return;
                            }
                        }
                    }
                }
                else
                {
                    strAlert = rm.GetString("TemporaryWeekDaySetting_Already_Exists", ci);
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("TemporaryWeekDaySetting_Already_Exists", ci) + "');", true);
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex);
            }
        }
        else
        {
            strAlert = rm.GetString("Msg_GrearterThanFrmDate", ci);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_GrearterThanFrmDate", ci) + "');", true);
            txtWeekFromDate.Focus();
            return;
        }
    }
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("Organization_Tempweekdaylist.aspx");
    }
    protected void btnLoadShift_Click(object sender, EventArgs e)
    {
        LoadShift();
    }
    #endregion
}
