/**
 * Licensed Materials - Property of IBM* and/or HCL**
 * UrbanCode Deploy
 * (c) Copyright IBM Corporation 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
 */

import java.nio.charset.Charset
import java.util.Collections
import java.util.HashMap
import java.util.Map
import java.io.IOException

import com.urbancode.air.AirPluginTool
import com.urbancode.commons.util.IO
import com.urbancode.ud.client.ComponentClient
import com.urbancode.ud.client.VersionClient

import com.urbancode.plugins.nuget.NuGetHelper
import com.urbancode.plugins.nuget.NuGetVersion

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

final Properties agentinProps = new Properties()
agentinProps.load(new FileInputStream(new File(System.getenv('AGENT_HOME'), 'conf/agent/installed.properties')))
String charsetName = agentinProps.getProperty('system.default.encoding')
Charset charset = null
if (charsetName != null) {
    charset = Charset.forName(charsetName)
}

String nuGetHost = inProps['nuGetHost'].trim()
String nuGetPackage = inProps['nuGetPackage'].trim()
boolean preRelease = Boolean.parseBoolean(inProps['prerelease'])
String username  = inProps['user'].trim()
String password  = inProps['password']
String proxyHost = inProps['proxyHost']?.trim()
int proxyPort    = inProps['proxyPort']?.trim() ? Integer.parseInt(inProps['proxyPort'].trim()) : -1
String proxyUser = inProps['proxyUser']?.trim()
String proxyPass = inProps['proxyPass']?.trim()
boolean trustAllCerts = Boolean.parseBoolean(inProps['trustAllCerts'])

boolean isUseVFS = Boolean.parseBoolean(inProps['isUseVFS'])
boolean preserveExecutePermissions = Boolean.valueOf(inProps['saveFileExecuteBits'])
boolean extensions = Boolean.parseBoolean(inProps['extensions'])

String nuGetVersionName  = inProps['versionName']?.trim()
String nuGetVersion = inProps['version']?.trim()
String description = inProps['description']?.trim()

if (description == null) {
    description = ""
}

String componentName = inProps['componentName']
String UDUsername = 'PasswordIsAuthToken'
String UDPassword = String.format('{\"token\": \"%s\"}', System.getenv('AUTH_TOKEN'))

String webString = System.getenv('AH_WEB_URL')
URI webUrl = new URI(webString)

VersionClient versionClient = new VersionClient(webUrl, UDUsername, UDPassword)
ComponentClient componentClient = new ComponentClient(webUrl, UDUsername, UDPassword)

NuGetHelper nh = new NuGetHelper(nuGetHost, nuGetPackage, preRelease, username, password, proxyHost, proxyPort,
    proxyUser, proxyPass, trustAllCerts)

try {
    List<NuGetVersion> nvList = nh.getVersionList()

    if (nvList.size() > 0) {

        // Gather all known UCD component versions
        List<String> versions = componentClient.getComponentVersions(componentName, false)
        List<String> archivedVersions = componentClient.getArchivedComponentVersions(componentName)
        versions.addAll(archivedVersions)

        // Retrieve specified version
        if (nuGetVersion) {
            List<NuGetVersion> newNvList = new ArrayList<NuGetVersion>()
            nvList.each { nv ->
                if (nv.version == nuGetVersion) {
                    nv.name = nuGetVersionName
                    newNvList.add(nv)
                }
            }

            // Should never be thrown
            if (newNvList.size() > 1) {
                throw new Exception("[Error] Found ${newNvList.size()} '${nuGetVersion}' versions when " +
                    "a single version was expected.");
            } else if (newNvList.size() == 0) {
                throw new Exception("[Error] Unable to find '${nuGetVersion}' version. " +
                    "Identified NuGet version(s): ${nvList*.version}");
            }

            nvList = newNvList
        }

        // Remove all previously imported versions
        List<NuGetVersion> removeNv = new ArrayList<NuGetVersion>()
        for (NuGetVersion nv : nvList) {
            for (String v : versions) {
                if (nv.getName() == v) {
                    removeNv.add(nv)
                }
            }
        }
        nvList.removeAll(removeNv)

        if (nvList.size() > 0) {

            // Default includes, excludes, and extensions. Only one file to export from NuGet repos
            String[] includes = ["*.nupkg"] as String[]
            String[] excludes = [] as String[]
            String[] extensionsList = [""] as String[]
            if (extensions) {
                extensionsList = [".nupkg"] as String[]
            }

            println "[Info] Found ${nvList.size()} new version(s)!"
            for (NuGetVersion nv : nvList) {
                println ""
                println "[Action] Creating version: `${nv.getName()}`"

                // Create version and add files
                if (isUseVFS) {
                    File tempDir = null
                    try {
                        Map<String,String> props = new HashMap<String, String>();
                        props.put("id", nv.id);
                        props.put("pkgTitle", nv.pkgTitle);
                        props.put("title", nv.title);
                        props.put("updated", nv.updated);
                        props.put("content", nv.content);
                        props.put("description", nv.description);
                        props.put("version", nv.version);
                        props.put("filename", isUseVFS ? nv.getFilename() : "");
                        tempDir = nh.download(nv);
                        String versionId = versionClient.createAndAddVersionFiles(componentName, nv.getName(),
                                description, tempDir, "", includes, excludes, preserveExecutePermissions, true, charset, extensionsList,
                                props, Collections.emptyMap()).toString()
                        apTool.setOutputProperty("VersionID", versionId)
                    } finally {
                        // Delete temporary download folder
                        try {
                            if (tempDir != null && tempDir.exists()) {
                                IO.delete(tempDir)
                            }
                        }
                        catch (IOException e) {
                            System.err.println(String.format("[Error] Unable to delete download directory", e.getMessage()))
                        }
                    }
                // Create version only
                } else {
                    String versionId = versionClient.createVersion(componentName, nv.getName(), description, true).toString()
                    versionClient.markImportFinished(componentName, versionId)
                    apTool.setOutputProperty("VersionID", versionId)
                    println "[Info] Not uploading artifact(s) to VFS."
                }

            }
            println ""
            println "[Info] Import(s) successful!"
        } else {
            println "[Info] No new NuGet Versions found."
        }

    } else {
        println "[Error] Unable to find list of NuGet Versions."
        System.exit(1)
    }
} finally {
    nh.closeClient()
}
