/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Release
 * (c) Copyright IBM Corporation 2015. All Rights Reserved.
 *
 * U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
 * GSA ADP Schedule Contract with IBM Corp.
 */
package com.urbancode.air.plugin.automation

import java.text.SimpleDateFormat

import org.codehaus.jettison.json.JSONException

import com.urbancode.release.rest.framework.Clients
import com.urbancode.release.rest.models.Change
import com.urbancode.release.rest.models.internal.PluginIntegrationProvider

class UCRClient {
    def integrationProviderId   // id of the integration provider that is running the script
    def integrationProvider //
    def lastExecutionDate  // the last date the integration was run
    def ucrServerUrl    // used to call ucr rest endpoint from the script
    def ucrToken        // token used to authenticate with the ucr server
    def existingChangesMap  // ALM changes existing on ucr server already 'id : change'

    public UCRClient(def props) {
        // default ucr properties
        integrationProviderId = props['releaseIntegrationProvider']
        ucrServerUrl = props['releaseServerUrl']
        ucrToken = props['releaseToken']
    }

    // authenticate with uRelease server
    private def releaseAuthentication() {
        try {
            Clients.loginWithToken(ucrServerUrl, ucrToken)
        }
        catch (JSONException ex) {
            println('Could not login with token.')
            throw new RuntimeException("JSONException: ${ex.getMessage()}")
        }
    }

    // initialize the plugin integration provider
    private void init() {
        releaseAuthentication()

        integrationProvider = new PluginIntegrationProvider().id(integrationProviderId).get()

        // We need to make sure that all changes or initiatives imported from that integration won't be editable
        integrationProvider.disabledFields("change", "type", "name", "status", "release", "application",
            "description", "severity", "initiative", "description", "name")
        integrationProvider.save()

        // get properties on ucr
        def ucrChanges = new Change().getAllForIntegrationProvider(integrationProviderId)
        println("Existing ALM changes on the UCR server: ${ucrChanges.size()}")

        // last date that the integration was run
        def lastExecution = integrationProvider.getProperty("lastExecution")

        if (lastExecution) {
            lastExecutionDate = new SimpleDateFormat("MM/dd/yyyy").parse(lastExecution)
            println("Last Execution Date: ${lastExecutionDate}")
        }

        // map each existing change to it's id
        existingChangesMap = [:]

        for (def existingChange : ucrChanges) {
            existingChangesMap.put(existingChange.getExternalId(), existingChange)
        }

    }

    // remove all HP ALM changes for this integration provider from the UCR server
    private void deleteAllChanges() {
        new Change().deleteAllForIntegrationProvider(integrationProviderId)
        println("All HP ALM changes have been removed from the Urbancode Release server.")
        integrationProvider.property("lastExecution", "").save()
    }
}