/**
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (c) Copyright IBM Corporation 2011, 2016. All Rights Reserved.
 *
 * U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
 * GSA ADP Schedule Contract with IBM Corp.
 */

import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.openshift.OpenShiftClient
import com.urbancode.ud.client.ComponentClient
import com.urbancode.ud.client.VersionClient

final String VERSION_DOCKER_IMAGE_TAG     = "dockerImageTag"; // Docker tag, like "latest"
final String VERSION_DOCKER_IMAGE_ID      = "dockerImageId";   // Docker id, 64 character check sum for the ID - soon to be deprecated in favor of signature
final String VERSION_OPENSHIFT_CREATED    = "osCreated";
final String VERSION_OPENSHIFT_DIR        = "osDockerImageReference";
final String VERSION_OPENSHIFT_FULL_IMAGE = "osImage";
final String VERSION_OPENSHIFT_GENERATION = "osGeneration";

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

String componentName    = props['componentName']
String namingConvention = props['namingConvention']
String openshiftServer  = props['openshiftServer']

String ucdUsername = "PasswordIsAuthToken"
String ucdPassword = String.format("{\"token\": \"%s\"}", System.getenv("AUTH_TOKEN"))
URI webUrl = new URI(System.getenv("AH_WEB_URL"))

OpenShiftClient client = new OpenShiftClient(props)

try {
    ArrayList tags = client.getTags()
    Map tagIdLabels = [:]
    tags.each { tag ->
        String id = client.getIdForTag(tag)
        Map<String,String> labels = new HashMap<String,String>()
        labels.putAll(client.getLabelsForTag(tag) ?: new HashMap<String,String>())
        if (id) {
            tagIdLabels.put(client.getTagIdForTag(tag), [id, labels,
                 client.getCreatedForTag(tag),
                 client.getDockerImageReferenceForTag(tag),
                 client.getImageForTag(tag),
                 client.getGenerationForTag(tag)])
        }
    }

    ComponentClient componentClient = new ComponentClient(webUrl, ucdUsername, ucdPassword);
    VersionClient versionClient;

    List<String> existingVersions = componentClient.getComponentVersions(componentName, true);

    tagIdLabels.each {
        String tag     = it.key
        String id      = it.value[0]
        String shortId = id.substring(0,7)
        HashMap<String, String> labels = it.value[1]
        String created    = it.value[2]
        String dIR        = it.value[3]
        String fullImage  = it.value[4]
        String generation = it.value[5]
        String versionName

        switch (namingConvention) {
            case "hyphenated":
                versionName = tag + " - " + shortId
                break
            case "space":
                versionName = tag + " " + shortId
                break
            case "tag_only":
                versionName = tag
                break
        }
        if (!existingVersions.contains(versionName)) {
            versionClient = new VersionClient(webUrl, ucdUsername, ucdPassword);
            println "[Action] Creating new version, ${versionName}"
            String versionId = versionClient.createVersion(componentName, versionName, "Imported from ${openshiftServer?:"localhost"}", true)
            apTool.setOutputProperty("VersionID", versionId);
            versionClient.setVersionProperty(versionName, componentName, VERSION_DOCKER_IMAGE_TAG, tag, false)
            versionClient.setVersionProperty(versionName, componentName, VERSION_DOCKER_IMAGE_ID, id, false)
            versionClient.setVersionProperty(versionName, componentName, VERSION_OPENSHIFT_CREATED, created, false)
            versionClient.setVersionProperty(versionName, componentName, VERSION_OPENSHIFT_DIR, dIR, false)
            versionClient.setVersionProperty(versionName, componentName, VERSION_OPENSHIFT_FULL_IMAGE, fullImage, false)
            versionClient.setVersionProperty(versionName, componentName, VERSION_OPENSHIFT_GENERATION, generation, false)
            labels.each { key, value ->
                println "[Action] Adding property ${key}=${value} for version ${versionName}"
                versionClient.setVersionProperty(versionName, componentName, key, value, false)
            }
            versionClient.markImportFinished(componentName, versionId);
            versionClient.client.close();
        }
        else {
            println "[Ok] Version, '${versionName}' already exists. Skipping..."
        }
    }
}
finally {
    client.logout()
    apTool.storeOutputProperties();
}

println "[Ok] Import Complete"
