/**
 * 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.commons.httpcomponentsutil.HttpClientBuilder
import org.apache.http.impl.client.DefaultHttpClient
import com.urbancode.air.AirPluginTool
import com.urbancode.air.XTrustProvider
import org.apache.http.HttpResponse
import org.apache.http.HttpStatus
import org.apache.http.client.methods.HttpGet
import java.util.regex.Matcher
import java.util.regex.Pattern
import org.apache.http.client.utils.URIBuilder
import java.net.URI
import groovy.json.JsonSlurper

import com.urbancode.air.plugin.docker.ICSClient
import com.urbancode.air.plugin.docker.RegistryClient
import com.urbancode.air.plugin.docker.OpenShiftClient
import com.urbancode.ud.client.ComponentClient
import com.urbancode.ud.client.VersionClient

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

if (props['dockerRegistryName'] == null || props['dockerRegistryName'].size() == 0) {
    props['dockerRegistryName'] = 'index.docker.io'
}
def registry = props['dockerRegistryName']
def componentName = props['componentName']
def namingConvention = props['namingConvention']
def dockerImageName = props['dockerImageName']
def registryType = props['registryType']

String ucdUsername = "PasswordIsAuthToken"
String ucdPassword = String.format("{\"token\": \"%s\"}", System.getenv("AUTH_TOKEN"))
def webUrl = new URI(System.getenv("AH_WEB_URL"))
def client
if (registryType.equals('true')) {
    client = new ICSClient(props)
}
else {
    client = new RegistryClient(props)
}

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

HashMap<String,String> openShiftLabels = new HashMap<String,String>()
if (registryType.equals('openshift')) {
    def openShiftImageName = dockerImageName.split('/')
    if (openShiftImageName.size() == 2) {
        OpenShiftClient.switchToProject(openShiftImageName.first())
    }
    openShiftLabels = OpenShiftClient.getLabels(openShiftImageName.last())
    if (!openShiftLabels) {
        println '[Error] Could not get imagestream Labels from OpenShift.'
        System.exit(1)
    }
    println ''
}

def tags = client.getTags()
def tagIdLabels = [:]
tags.each { tag ->
    def id = client.getIdForTag(tag)
    def labels = client.getLabelsForTag(tag)
    labels.putAll(openShiftLabels)
    if (id) {
        tagIdLabels.put(tag, [id, labels])
    }
}

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

def existingVersions = componentClient.getComponentVersions(componentName, true);

tagIdLabels.each {
    def tag = it.key
    def id = it.value[0]
    def labels = it.value[1]
    def shortId = id.substring(0,7)
    def 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)) {
        println "[Action] Creating new version, $versionName"
        versionClient.createVersion(componentName, versionName, "Imported from $registry")
        versionClient.setVersionProperty(versionName, componentName, VERSION_DOCKER_IMAGE_TAG, tag, false)
        versionClient.setVersionProperty(versionName, componentName, VERSION_DOCKER_IMAGE_ID, id, false)
        labels.each { key, value ->
            println "[Action] Adding property ${key}=${value} for version ${versionName}"
            versionClient.setVersionProperty(versionName, componentName, key, value, false)
        }
    }
    else {
        println "[Ok] Version, '$versionName' already exists. Skipping..."
    }
}

println "[Ok] Import complete"
