B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Activity
Version=9.9
@EndOfDesignText@
#Region  Activity Attributes 
    #FullScreen: False
    #IncludeTitle: True
    #IgnoreWarnings: 15, 9
#End Region

Sub Process_Globals
    Private UpdateTimer As Timer
End Sub

Sub Globals
    Private wvMap As WebView
    Private lblBusInfo As Label
    Private lblETA As Label
    Private btnRefresh As Button
    
    Private CurrentStudent As Map
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.Title = "Track Bus"
    
    ' Load selected student
    If File.Exists(File.DirInternal, "selected_student.json") Then
        Dim parser As JSONParser
        parser.Initialize(File.ReadString(File.DirInternal, "selected_student.json"))
        CurrentStudent = parser.NextObject
    Else
        ToastMessageShow("No student selected", True)
        Activity.Finish
        Return
    End If
    
    InitializeUI
    
    UpdateTimer.Initialize("UpdateTimer", 5000) ' Update every 5 seconds
    UpdateTimer.Enabled = True
End Sub

Sub InitializeUI
    ' Info Panel
    lblBusInfo.Initialize("")
    lblBusInfo.Text = "Bus: " & CurrentStudent.GetDefault("bus_number", "N/A")
    lblBusInfo.TextSize = 18
    lblBusInfo.Gravity = Gravity.CENTER
    Activity.AddView(lblBusInfo, 0, 0, 100%x, 50dip)
    
    lblETA.Initialize("")
    lblETA.Text = "Fetching location..."
    lblETA.TextSize = 16
    lblETA.Gravity = Gravity.CENTER
    Activity.AddView(lblETA, 0, 50dip, 100%x, 40dip)
    
    ' Map Web View
    wvMap.Initialize("wvMap")
    Activity.AddView(wvMap, 0, 90dip, 100%x, 100%y - 150dip)
    wvMap.LoadUrl("file:///android_asset/map.html")
    
    ' Refresh Button
    btnRefresh.Initialize("btnRefresh")
    btnRefresh.Text = "Refresh Location"
    Activity.AddView(btnRefresh, 10%x, 100%y - 60dip, 80%x, 50dip)
End Sub

Sub UpdateMap(busLat As Double, busLon As Double, stopLat As Double, stopLon As Double, routeStopsJson As String)
    ' Calls Javascript in the WebView
    Dim jo As JavaObject = wvMap
    ' Escaping quotes for JS call
    Dim escapedJson As String = routeStopsJson.Replace("'", "\'")
    jo.RunMethod("evaluateJavascript", Array("updatePositions(" & busLat & "," & busLon & "," & stopLat & "," & stopLon & ",'" & escapedJson & "')", Null))
End Sub

Sub Activity_Resume
    FetchBusLocation
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    UpdateTimer.Enabled = False
End Sub

Sub UpdateTimer_Tick
    FetchBusLocation
End Sub

Sub btnRefresh_Click
    FetchBusLocation
End Sub

Sub FetchBusLocation
    Dim studentId As Int = CurrentStudent.GetDefault("id", 0)
    If studentId = 0 Then Return
    
    Dim job As HttpJob
    job.Initialize("get_eta", Me)
    job.Download(APIModule.ServerURL & "/get_eta.php?student_id=" & studentId)
End Sub

Sub JobDone(Job As HttpJob)
    If Job.Success Then
        If Job.JobName = "get_eta" Then
            Try
                Dim parser As JSONParser
                parser.Initialize(Job.GetString)
                Dim root As Map = parser.NextObject
                
                If True = root.Get("success") Then
                    Dim eta As Int = root.Get("eta_minutes")
                    Dim dist As Double = root.Get("distance_km")
                    Dim busNumber As String = root.Get("bus_number")
                    
                    lblBusInfo.Text = "Bus: " & busNumber & " (" & dist & " km away)"
                    lblETA.Text = "Estimated Arrival: " & eta & " minutes"
                    lblETA.TextColor = Colors.RGB(33, 150, 243)
                    
                    ' Update Map positions
                    Dim busLat As Double = root.Get("bus_lat")
                    Dim busLon As Double = root.Get("bus_lon")
                    Dim stopLat As Double = root.Get("student_lat")
                    Dim stopLon As Double = root.Get("student_lon")
                    
                    Dim routeStops As List = root.Get("route_stops")
                    Dim gen As JSONGenerator
                    gen.Initialize2(routeStops)
                    
                    UpdateMap(busLat, busLon, stopLat, stopLon, gen.ToString)
                Else
                    Dim errorMsg As String = root.Get("error")
                    lblETA.Text = "Status: " & errorMsg
                    lblETA.TextColor = Colors.Red
                End If
            Catch
                Log("Error parsing ETA: " & LastException)
                lblETA.Text = "Error calculating ETA"
            End Try
        End If
    Else
        lblETA.Text = "Network error"
        Log("Network error: " & Job.ErrorMessage)
    End If
    Job.Release
End Sub
