<?xml version="1.0" encoding="utf-8" ?>

<component name="TagTask" extends="Task">

<interface>
  <field id="updateText" type="string" value="Tagging from TagTask"/>
</interface>
<children>
  <Settings id="MySettings" />
</children>

<script type="text/brightscript" >
<![CDATA[

sub init()
    m.top.functionName = "executeTask"
    m.settings = m.top.findNode("MySettings")
end sub

function getDeviceId(deviceInfo as object) as String
    ' Try to get the Serial Number for an ECP call
    request = CreateObject("roUrlTransfer")
    request.SetUrl("http://localhost:8060/query/device-info")
    root = CreateObject("roXMLElement")
    if root.Parse(request.GetToString()) then
        serialnums = root.GetNamedElements("serial-number")
        if serialnums.Count() > 0
            model = root.GetNamedElements("model-number")
            if model.Count() > 0
                return serialnums[0].GetText() + ":" + model[0].GetText()
            end if
        end if
    end if
    ' That did not work, so make a custom one.
    clientID = Right(deviceInfo.GetChannelClientId(), 8)
    return clientID + ":" + deviceInfo.GetModelDetails()["ModelNumber"]
end function

function executeTask() as void
    m.port = CreateObject("roMessagePort")

    deviceInfo = CreateObject("roDeviceInfo")

    aaIPAddrs = deviceInfo.GetIPAddrs()
    for each key in aaIPAddrs
        ipAddr = aaipAddrs[key]
        if ipAddr <> invalid and ipAddr.Len() > 0
            ' m.top.updateText = key + " = " + ipAddr
        end if
    end for

    sendRequest(ipAddr, getDeviceId(deviceInfo))
end function

sub sendRequest(ipAddr as String, deviceID as String)
    request = CreateObject("roUrlTransfer")
    request.SetCertificatesFile("common:/certs/ca-bundle.crt")
    request.SetPort(m.port)
    request.SetUrl(m.settings.url)
    params = deviceID+"="+ipAddr+"&auth="+m.settings.auth
    m.top.updateText = "Tagging "+ipAddr+" for "+deviceID+"..."
    if request.AsyncPostFromString(params)
        print "Request was sent!"
    endif

    while true
        msg = wait(0, m.port)
        if type(msg) = "roUrlEvent"
            if msg.GetInt() = 1
                if msg.GetResponseCode() = 200
                    m.top.updateText = "Success!" + chr(10) + "You can get this device's IP address with:"
                    m.top.updateText = m.settings.url+"?k="+deviceID
                else
                    m.top.updateText = "It didn't work. Got code " + str(msg.GetResponseCode())
                endif
            endif
        end if
    end while
end sub

]]>
</script>
</component>
