/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* (c) Copyright IBM Corporation 2013, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/
package com.urbancode.air.plugin.webutilities

import org.apache.http.HttpEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.util.EntityUtils

/**
 * Defines the default response property
 *
 * @param   response    Accepts any response entity.
 * @param   outFile     The java File object to use for the output.
 * @param   outputProps Output properties hashmap.
 * @return              A hashmap of the outputs.
 */
public static Map hTTPResponseProcessing(CloseableHttpResponse response, File outFile, Properties outputProps) {
    outputProps['responseStatus'] = response.getStatusLine().getStatusCode().toString()
    response.getAllHeaders().each { header ->
        outputProps[header.name] = header.value.toString()
    }
    HttpEntity entity = response.getEntity()
    if(entity){
        File entityTempFile = File.createTempFile('httpresponse', '', new File('.'))
        entityTempFile.deleteOnExit()
        FileOutputStream entityTempFileIOStream = new FileOutputStream(entityTempFile)
        entity.writeTo(entityTempFileIOStream)

        //TODO: Set this output property if the response entity is a readable content
        outputProps["responseBody"] = entityTempFile.getText()
        entityTempFileIOStream.close()
        if(outFile){      
            entityTempFile.renameTo(outFile)
        }
    }
    else {
        outputProps["responseBody"] = ""
    }
    return outputProps
}
