import com.fasterxml.jackson.databind.ObjectMapper

// Analysis job ID shown in the output of Script 5 
def API_KEY = "your API key"
def ANALYSIS_JOB_ID = "your job ID"

// Endpoints
def GET_URL = "https://app.biodock.ai/api/external/analysis-jobs/${ANALYSIS_JOB_ID}/"
def POST_URL = "https://app.biodock.ai/api/external/analysis-jobs/${ANALYSIS_JOB_ID}/download-masks"

// Prepare and execute the GET request
def getUrl = new URL(GET_URL)
def getConnection = getUrl.openConnection() as HttpURLConnection
getConnection.setRequestProperty("X-API-KEY", API_KEY)
getConnection.setRequestProperty("Content-Type", "application/json")

def getResponseCode = getConnection.responseCode
def getResponseText = (getResponseCode >= 200 && getResponseCode < 300) ? 
    getConnection.inputStream.text : getConnection.errorStream?.text

// Prepare and execute the POST request
def postUrl = new URL(POST_URL)
def postConnection = postUrl.openConnection() as HttpURLConnection
postConnection.setRequestMethod("POST")
postConnection.setRequestProperty("X-API-KEY", API_KEY)
postConnection.setRequestProperty("Content-Type", "application/json")
postConnection.doOutput = true

def postResponseCode = postConnection.responseCode
def postResponseText = (postResponseCode >= 200 && postResponseCode < 300) ? 
    postConnection.inputStream.text : postConnection.errorStream?.text

// Print subset of keys and values
def printJsonObject(obj, indent = "") {
    if (obj instanceof Map) {
        // obj is another JSON object
        obj.each { k, v ->
            println("${indent}${k} :")
            printJsonObject(v, indent + "    ")
        }
    } else if (obj instanceof List) {
        // obj is a JSON array
        obj.eachWithIndex { val, i ->
            println("${indent}[${i + 1}] :")
            printJsonObject(val, indent + "    ")
        }
    } else {
        // obj is a simple value (string, number, boolean, null)
        println("${indent}${obj}")
    }
}

// Parse the JSON response using Jackson ObjectMapper
def mapper = new ObjectMapper()
def data1 = mapper.readValue(getResponseText, Map)
def data2 = mapper.readValue(postResponseText, Map)

// Convert the keySet of the map to a list
def keys1 = new ArrayList(data1.keySet())
def keys2 = new ArrayList(data2.keySet())

// Define a custom range for end index
def endIndex1 = keys1.size() - 1
def endIndex2 = keys2.size() - 1

// Print the responses
for (int i = 0; i <= endIndex1; i++) {
    def k = keys1[i]
    println("${k} :")
    printJsonObject(data1[k], "    ")
}
println("\n\n")
for (int i = 0; i <= endIndex2; i++) {
    def k = keys2[i]
    println("${k} :")
    printJsonObject(data2[k], "    ")
}
