/*
* Licensed Materials - Property of HCL
* UrbanCode Build
* (c) Copyright HCL Technologies Ltd. 2019. All Rights Reserved.
*/
import com.urbancode.air.AirPluginTool
import com.urbancode.build.plugin.ucd.rest.UCDRestHelper

import org.apache.log4j.Level
import org.apache.log4j.Logger

//------------------------------------------------------------------------------
// GET ALL INPUT PARAMETERS
//------------------------------------------------------------------------------
final File workDir = new File('.').canonicalFile
final String javaHome = System.getenv('JAVA_HOME')
final String pluginHome = System.getenv("PLUGIN_HOME")
final String webUrl = System.getenv('WEB_URL')
final String buildLifeId = System.getenv('BUILD_LIFE_ID')

final AirPluginTool apTool = new AirPluginTool(this.args[0], this.args[1])
final Properties props = apTool.getStepProperties()

final File javaFile = new File(new File(javaHome),
    'bin' + File.pathSeparator + 'java' + (apTool.isWindows ? '.exe' : ''))
final File udClientJarFile = new File(new File(pluginHome),
    'lib' + File.pathSeparator + 'udclient.jar')

String ucdUrl = props['automation/url']
String ucdUser = props['automation/user']
String ucdPassword = props['automation/passScript'] ?: props['automation/password']
String ucdAuthToken = props["job/ucdUserAuthToken"] ?: props["buildlife/ucdUserAuthToken"] ?: props['automation/authToken']
String environment = props['environment']
String application = props['application']
String snapshot = props['snapshotName']
String description = props['description']?.trim()
String versionMappings = props['versionMappings']?.trim()   // Mapping of component/version
String excludeUnmapped = Boolean.valueOf(props['excludeUnmapped'])

/*Configure Log4j logger */
String logLevel = props['loggerLevel']
Logger.getRootLogger().setLevel(Level.toLevel(logLevel)) // Configure log level for all loggers
Logger logger = Logger.getLogger(getClass()) // Get the logger for this class

UCDRestHelper ucdHelper = new UCDRestHelper(ucdUrl, ucdUser, ucdPassword, ucdAuthToken)

String snapshotId = ucdHelper.createEnvironmentSnapshot(environment, application,
    snapshot, description)
logger.info("Successfully created environment snapshot.")

if (versionMappings) {
    Map<String, List<String>> versionMap = new HashMap<String, String>() // component:version map

    for (String mapping : versionMappings.tokenize("\n")*.trim()) {
        List<String> entry = mapping.split("/", 2)*.trim()
        if (entry.size() > 1) {
            String component = entry.get(0)
            String version = entry.get(1)

            List<String> versions = null
            /* Get list of versions if it contains entries for this component */
            if (versionMap.containsKey(component)) {
                versions = versionMap.get(component)
            }
            /* Create new list if no other entries exist yet for this component */
            else {
                versions = new ArrayList<String>()
            }

            /* Add the new version to the list and map it to the component */
            versions.add(version)
            versionMap.put(component, versions)
        }
    }

    ucdHelper.updateSnapshotVersions(snapshotId, application, versionMap)

    logger.info("Successfully added component versions to snapshot.")
}

apTool.setOutputProperty("snapshotId", snapshotId)
apTool.storeOutputProperties()
