Imports System.Collections.Generic
Imports System.Text
Imports CharterDotCom.CommonEntities.Library
Imports CharterDotCom.CommonEntities.Library.Enumerations
Imports CharterDotCom.CommonEntities.Library.EntityMemberServices
'Imports CharterDotCom.CommonEntities.Library.EntityEBSServices
Imports CharterDotCom.CommonEntities.Library.EntitySupport
Imports CharterDotCom.CommonEntities.Library.EntitySearch
Imports CharterDotCom.CommonEntities.Library.EntityWebConfig
'Imports CharterDotCom.CommonEntities.Library.EntityG2BServices
Imports CharterDotCom.CommonEntities.Library.Common
Imports CharterDotCom.WebSite.Library

Partial Class Controls_ScheduleInstallation
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim schedule1 As IOrder.ISchedule = Nothing
        Dim schedule2 As IOrder.ISchedule = Nothing
        Dim sb As StringBuilder
        'Dim _order As Order
        'Dim _appointments As List(Of TimeSlot)

        If Not IsPostBack Then
            pnlFirst.Visible = False
            pnlSecond.Visible = False

            Dim _confirmations As Dictionary(Of String, IConfirmation) = Nothing
            Dim _confirmation As KeyValuePair(Of String, IConfirmation) = Nothing

            OrderManager.Instance.GetConfirmationInfo(_confirmations)

            If _confirmations IsNot Nothing Then
                sb = New StringBuilder()
                For Each _confirmation In _confirmations
                    sb.AppendFormat("{0}: {1}<br />", _confirmation.Key, _confirmation.Value.Number)
                Next
                lblConfirmation.Text = sb.ToString()
            End If


            btnNext.Attributes.Add("onclick", "return validate()")

            OrderManager.Instance.GetSchedule(schedule1, schedule2)

            If schedule1 IsNot Nothing Then
                If schedule1.ScheduleWindow.Count > 0 Then
                    ViewState(Me.ID + "_FirstType") = schedule1.Type

                    Select Case schedule1.Type
                        Case ScheduleType.All
                            lblFirst.Text = "Cable TV, High-Speed Internet, and Telephone Services"
                        Case ScheduleType.Cable
                            lblFirst.Text = "Cable TV Service"
                        Case ScheduleType.CableAndHSD
                            lblFirst.Text = "Cable TV and High-Speed Internet Services"
                        Case ScheduleType.CableAndTelephone
                            lblFirst.Text = "Cable TV and Telephone Services"
                        Case ScheduleType.HSD
                            lblFirst.Text = "High-Speed Internet Service"
                        Case ScheduleType.HSDAndTelephone
                            lblFirst.Text = "High-Speed Internet and Telephone Services"
                        Case ScheduleType.Telephone
                            lblFirst.Text = "Telephone Service"
                    End Select

                    ltrFirst.Text = RenderSlots(schedule1, "First")

                    pnlFirst.Visible = True
                End If
            End If

            If schedule2 IsNot Nothing Then
                If schedule2.ScheduleWindow.Count > 0 Then
                    ViewState(Me.ID + "_SecondType") = schedule2.Type

                    Select Case schedule1.Type
                        Case ScheduleType.All
                            lblSecond.Text = "Cable TV, High-Speed Internet, and Telephone Services"
                        Case ScheduleType.Cable
                            lblSecond.Text = "Cable TV Service"
                        Case ScheduleType.CableAndHSD
                            lblSecond.Text = "Cable TV and High-Speed Internet Services"
                        Case ScheduleType.CableAndTelephone
                            lblSecond.Text = "Cable TV and Telephone Services"
                        Case ScheduleType.HSD
                            lblSecond.Text = "High-Speed Internet Service"
                        Case ScheduleType.HSDAndTelephone
                            lblSecond.Text = "High-Speed Internet and Telephone Services"
                        Case ScheduleType.Telephone
                            lblSecond.Text = "Telephone Service"
                    End Select

                    ltrSecond.Text = RenderSlots(schedule2, "Second")

                    pnlSecond.Visible = True
                End If
            End If

            If pnlFirst.Visible = False And pnlSecond.Visible = False Then
                'pInstruction.Visible = False
                '	lblError.Text = "No schedules are available."
                Response.Redirect("FinishOrder.aspx?" + QueryStringName.OrderComplete + "=false")
            End If
        End If
    End Sub

    Private Function RenderSlots(ByVal schedule As IOrder.ISchedule, ByVal scheduleName As String) As String
        Dim slots As Dictionary(Of DateTime, Dictionary(Of String, IOrder.IScheduleWindow))
        Dim slot As Dictionary(Of String, IOrder.IScheduleWindow)
        Dim windowPair As KeyValuePair(Of String, IOrder.IScheduleWindow)
        Dim startDate As DateTime = DateTime.MinValue
        Dim endDate As DateTime = DateTime.MinValue
        Dim currDate As DateTime
        Dim sb As StringBuilder = New StringBuilder()
        Dim sb1 As StringBuilder
        Dim sb2 As StringBuilder
        Dim i As Integer = 0

        slots = New Dictionary(Of DateTime, Dictionary(Of String, IOrder.IScheduleWindow))()

        For Each windowPair In schedule.ScheduleWindow
            If startDate = DateTime.MinValue Then
                startDate = Convert.ToDateTime(windowPair.Value.ScheduleDate)
                endDate = startDate
            End If

            While endDate < Convert.ToDateTime(windowPair.Value.ScheduleDate)
                If endDate.DayOfWeek <> DayOfWeek.Saturday And endDate.DayOfWeek <> DayOfWeek.Sunday Then
                    If Not slots.ContainsKey(endDate) Then
                        slots.Add(endDate, Nothing)
                    End If
                End If

                endDate = endDate.AddDays(1)
            End While

            If slots.ContainsKey(endDate) Then
                slots(endDate).Add(windowPair.Key, windowPair.Value)
            Else
                slot = New Dictionary(Of String, IOrder.IScheduleWindow)
                slot.Add(windowPair.Key, windowPair.Value)
                slots.Add(endDate, slot)
            End If
        Next

        While startDate.DayOfWeek <> DayOfWeek.Monday
            startDate = startDate.AddDays(-1)
            slots.Add(startDate, Nothing)
        End While

        While endDate.DayOfWeek <> DayOfWeek.Friday
            endDate = endDate.AddDays(1)
            slots.Add(endDate, Nothing)
        End While

        currDate = startDate

        sb1 = New StringBuilder()
        sb2 = New StringBuilder()

        'If currDate = DateTime.MinValue Then
        '	Throw New ApplicationException("No schedules were returned.")
        'End If

        While currDate <= endDate
            If currDate.DayOfWeek <> DayOfWeek.Saturday And currDate.DayOfWeek <> DayOfWeek.Sunday Then
                slot = slots(currDate)

                If currDate.DayOfWeek = DayOfWeek.Monday Then
                    sb1.AppendFormat("<tr class='calendarDay'><td><span>{0}</span> {1}", currDate.Day, currDate.DayOfWeek.ToString().Substring(0, 3))
                    sb2.Append("<tr class='calendarTime'><td>")
                Else
                    sb1.AppendFormat("<td><span>{0}</span> {1}", currDate.Day, currDate.DayOfWeek.ToString().Substring(0, 3))
                    sb2.Append("<td>")
                End If

                If slot Is Nothing Then
                    sb2.Append("<p>No appointment times available</p>")
                Else
                    For Each windowPair In slot
                        Dim startTime As String
                        Dim endTime As String
                        startTime = windowPair.Value.StartTime
                        endTime = windowPair.Value.EndTime
                        Try
                            startTime = Convert.ToDateTime("1/1/2006 " & startTime).ToShortTimeString
                            endTime = Convert.ToDateTime("1/1/2006 " & endTime).ToShortTimeString
                        Catch ex As Exception

                        End Try
                        sb2.AppendFormat("<input type='checkbox' name='chk{0}{1}' onclick=""javascript:chk{0}_click('{1}')"" title='{4}, arriving between {2} and {3}'>{2} - {3}</input><br />", _
                        scheduleName, windowPair.Value.ID, startTime, endTime, currDate.ToString("dddd, MMMM d"))
                    Next
                End If

                If currDate.DayOfWeek = DayOfWeek.Friday Then
                    sb1.Append("</td></tr>")
                    sb2.Append("</td></tr>")

                    If i Mod 2 = 0 Then
                        If i = 0 Then
                            sb.AppendFormat("<div id='tbl{0}{1}' style='display:block'><table id='scheduleWidget' cellpadding='0' cellspacing='0'>", scheduleName, i / 2)
                        Else
                            sb.AppendFormat("<div id='tbl{0}{1}' style='display:none'><table id='scheduleWidget' cellpadding='0' cellspacing='0'>", scheduleName, i / 2)
                        End If

                        sb.AppendFormat("<tr><th colspan='5' class='calendarTitle'>{0}</th></tr>", currDate.ToString("MMMM yyyy"))

                        sb.Append(sb1.ToString())
                        sb.Append(sb2.ToString())
                    Else
                        sb.Append(sb1.ToString())
                        sb.Append(sb2.ToString())

                        sb.Append("</table></div>")
                    End If

                    sb1 = New StringBuilder()
                    sb2 = New StringBuilder()

                    i = i + 1
                Else
                    sb1.Append("</td>")
                    sb2.Append("</td>")
                End If
            End If

            currDate = currDate.AddDays(1)
        End While

        If i Mod 2 = 1 Then
            sb.Append("</table></div>")
        End If

        'If i <= 2 Then
        '	If scheduleName = "First" Then
        '		lnkNextFirst.Style("visibility") = "hidden"
        '	Else
        '		lnkNextSecond.Style("visibility") = "hidden"
        '	End If
        'End If

        Return sb.ToString()
    End Function

    Protected Sub btnNext_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnNext.Click
        Dim firstType As ScheduleType
        Dim secondType As ScheduleType
        Dim firstIDs As List(Of String) = New List(Of String)()
        Dim secondIDs As List(Of String) = New List(Of String)()

        If Request.Form("txtFirst1") Is Nothing Or Request.Form("txtFirst1") = String.Empty Then
            ' do nothing
        Else
            firstIDs.Add(Request.Form("txtFirst1"))
        End If

        If Request.Form("txtFirst2") Is Nothing Or Request.Form("txtFirst2") = String.Empty Then
            ' do nothing
        Else
            firstIDs.Add(Request.Form("txtFirst2"))
        End If

        If Request.Form("txtSecond1") Is Nothing Or Request.Form("txtSecond1") = String.Empty Then
            ' do nothing
        Else
            secondIDs.Add(Request.Form("txtSecond1"))
        End If

        If Request.Form("txtSecond2") Is Nothing Or Request.Form("txtSecond2") = String.Empty Then
            ' do nothing
        Else
            secondIDs.Add(Request.Form("txtSecond1"))
        End If

        If ViewState(Me.ID + "_FirstType") IsNot Nothing Then
            firstType = CType(ViewState(Me.ID + "_FirstType"), ScheduleType)

            '##################################################################################
            'MODIFICATION   ROD COPELAND    FEB 01 2008
            'THIS CHANGE WAS REQUESTED BY SHARON RENAUD, JOE KESSLER, LINDA LAMBERT.
            '##################################################################################
            'COUNT FLAG IS RESET IN THE CONTROLS/SHOPPINGCART.ASCX.VB AT THIS TIME.
            'IN THE EVENT THE USER ENDS UP ON THIS PAGE BY HITTING F5 WHILE ITS LOADING 
            'OR NAVIGATING DIRECTLY TO IT, THE INTENT IS TO NOT SUBMIT THE WEB SERVICE CALL 
            'TWICE BY USING THIS FLAG.
            'TO CLEAR THESE FLAGS, THE USER WILL NEED TO CHECKOUT AGAIN.
            '##################################################################################
            If Not (Session("SUBMIT_SCHEDULE_COUNT") Is Nothing) Then
                '###########################
                'SKIP THE SUBMIT ORDER CALL
                '###########################

            Else
                '###########################
                'MAKE THE SUBMIT ORDER CALL
                '###########################
                Session("SUBMIT_SCHEDULE_COUNT") = Session("SUBMIT_SCHEDULE_COUNT") + 1

                If ViewState(Me.ID + "_SecondType") IsNot Nothing Then
                    secondType = CType(ViewState(Me.ID + "_SecondType"), ScheduleType)
                    OrderManager.Instance.SubmitSchedules(firstType.ToString, firstIDs, secondType.ToString, secondIDs)
                Else
                    OrderManager.Instance.SubmitSchedules(firstType.ToString, firstIDs, Nothing, Nothing)
                End If
            End If
        Else

        End If

        Response.Redirect("FinishOrder.aspx?" + QueryStringName.OrderComplete + "=true")
    End Sub

    'Private Function LoadAppointments(ByVal _category As Category, ByVal appointments As List(Of TimeSlot)) As String
    '	Dim name As String
    '	Dim startDate As DateTime
    '	Dim endDate As DateTime
    '	Dim currDate As DateTime
    '	Dim numberOfWeek As Integer
    '	Dim i As Integer
    '	Dim j As Integer
    '	Dim k As Integer
    '	Dim sb As StringBuilder
    '	Dim sb1 As StringBuilder
    '	Dim sb2 As StringBuilder

    '	Select Case _category
    '		Case Category.Cable
    '			name = "CableTV"
    '		Case Category.HSD
    '			name = "Internet"
    '		Case Category.Telephoney
    '			name = "Telephone"
    '		Case Else
    '			name = String.Empty
    '	End Select

    '	startDate = appointments(0).FromTime.AddDays((-1) * appointments(0).FromTime.DayOfWeek)
    '	endDate = appointments(appointments.Count - 1).FromTime.AddDays(6 - appointments(0).FromTime.DayOfWeek)

    '	numberOfWeek = endDate.Subtract(startDate).Days / 7

    '	sb = New StringBuilder()
    '	k = 0

    '	For i = 0 To numberOfWeek - 1
    '		sb1 = New StringBuilder("<tr>")
    '		sb2 = New StringBuilder("<tr>")

    '		For j = 1 To 5
    '			currDate = startDate.AddDays(i * 7 + j)

    '			If i Mod 2 = 0 Then
    '				sb1.AppendFormat("<th>{0}</th>", currDate.ToString("ddd MM/dd"))
    '			Else
    '				sb1.AppendFormat("<th style='border-top:solid 1px #000000'>{0}</th>", currDate.ToString("ddd MM/dd"))
    '			End If

    '			sb2.Append("<td>")

    '			Do
    '				If k >= appointments.Count Then
    '					Exit Do
    '				ElseIf currDate.Day = appointments(k).FromTime.Day Then
    '					sb2.AppendFormat("<input type='checkbox' name='chk{0}{1}' onclick='chk{0}_click({1})' title='{4}, arriving between {5} and {6}'>{2} - {3}</input><br />", _
    '					name, appointments(k).ID, appointments(k).FromTime.ToString("h tt"), appointments(k).ToTime.ToString("h tt"), _
    '					currDate.ToString("dddd, MMMM d"), appointments(k).FromTime.ToString("h:mm tt"), appointments(k).ToTime.ToString("h:mm tt"))
    '					k = k + 1
    '				Else
    '					Exit Do
    '				End If
    '			Loop

    '			sb2.Append("</td>")
    '		Next

    '		sb1.Append("</tr>")
    '		sb2.Append("</tr>")

    '		If i Mod 2 = 0 Then
    '			If i = 0 Then
    '				sb.AppendFormat("<table cellpadding='2' cellspacing='0' class='panel' style='font-size:9px;display:block' id='tbl{0}{1}'>", name, i / 2)
    '			Else
    '				sb.AppendFormat("<table cellpadding='2' cellspacing='0' class='panel' style='font-size:9px;display:none' id='tbl{0}{1}'>", name, i / 2)
    '			End If
    '		End If

    '		sb.Append(sb1.ToString())
    '		sb.Append(sb2.ToString())

    '		If i Mod 2 = 1 Then
    '			sb.AppendFormat("</table>")
    '		End If
    '	Next

    '	Return sb.ToString()
    'End Function
End Class
