import urllib, urllib2
from com.xebialabs.xltest.utils import JsonResponseParser

# From the url of the run, we lookup the details of the corresponding testSetDefinition and post a new URL to start
# a new run of that testSetDefinition
# That post yields a fresh run_id in the respons. We construct a new URL of the progress window and return that to the GUI
# The GUI open a new window on that new URL

testSetDefinition = testRun.getTestSetDefinition().getName()
type = testRun.getType()

url = testRun.getUri().toString()
lastSlashIndex = url.rfind('/')
url = url[:lastSlashIndex]

# start new run
content = '{"testSetDefinition":"Configuration/TestSetDefinitions/%s","type":"%s","id":""}' % (testSetDefinition, type)
req = urllib2.Request(url, data=content, headers={'Content-type': 'application/json'})

# get the run_id of the new run from the response. It is part of the property 'uri'
parser = JsonResponseParser();
parser.parse(urllib2.urlopen(req).read())
response_uri = parser.getValue("uri")
lastSlashIndex = response_uri.rfind('/')
run_id_of_new_run = response_uri[lastSlashIndex + 1:]

# compose the URL of the progress window from the old url and the new run_id
# strip '/test' from the url
url = url[:-5]
new_url = url + '/#/testruns/%s' % run_id_of_new_run


resultHolder.setResult(new_url)