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.RegistryClient
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']

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

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

def client = new RegistryClient(props)
def tags = client.getTags()
def tag2Id = [:]
tags.each { tag ->
    def id = client.getIdForTag(tag)
    if (id) {
        tag2Id.put(tag, id)
    }
}

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

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

tag2Id.each {
    def tag = it.key
    def id = it.value
    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 "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)
    }
    else {
        println "Version, '$versionName' already exists. Skipping..."
    }
}

println "Import complete"
