'*************************************************************
'** Roku Xtream-ALL for XoceUnder                            *
'** Copyright (c)2024 XoceUnder.  All rights reserved.       *
'*************************************************************
sub Init()
    ' set the name of the function in the Task node component to be executed when the state field changes to RUN
    ' in our case this method executed after the following cmd: m.contentTask.control = "run"(see Init method in MainScene)
    m.top.functionName = "GetContent"
end sub
 








 sub GetContent()
    date = CreateObject("roDatetime")
    
    for each content in m.top.content.GetChildren(-1, 0)
        ' Crear solicitud HTTP
 
               http = NewHttp( m.global.config.serverURL + "/player_api.php")
        http.contentHeader = "application/x-www-form-urlencoded"
        http.AddParam("username", m.global.user.Escape())
        http.AddParam("password", m.global.pass.Escape())
        http.AddParam("action", "get_short_epg".Escape())
        http.AddParam("limit", "7".Escape())
        http.AddParam("stream_id", content.id.Escape())

        ' Enviar solicitud
        request = http.Request()
        print "Respuesta API cruda: "; request

        ' Parsear JSON
        json = ParseJson(request)

        ' Validar que json es un objeto con epg_listings
        if Type(json) = "roAssociativeArray" and json.epg_listings <> invalid and json.epg_listings.Count() > 0
            for each channel in json.epg_listings
                program = content.createChild("ContentNode")

                ' Decodificar campos base64
                title = decodeBase64(channel.title)
                description = decodeBase64(channel.description)

                ' Calcular duración del programa
                startTime = evalInteger(channel.start_timestamp)
                endTime = evalInteger(channel.stop_timestamp)
                duration = Int(endTime - startTime)

                ' Asignar campos al nodo
                program.title = title
                program.description = description
                program.playStart = startTime
                program.playDuration = duration
                program.addFields({"playStop": endTime})
            end for
        else
            print "EPG no disponible o formato JSON inesperado para stream_id: "; content.id
        end if
    end for
end sub
