#!/usr/bin/env groovy
/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Release
 * (c) Copyright IBM Corporation 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.*

import java.net.URI
import java.net.URL
import java.nio.charset.Charset

import com.urbancode.commons.util.query.QueryFilter.FilterType
import com.urbancode.release.rest.framework.Clients
import com.urbancode.release.rest.framework.QueryParams.FilterClass
import com.urbancode.release.rest.models.Change
import com.urbancode.release.rest.models.Initiative
import com.urbancode.release.rest.models.internal.PluginIntegrationProvider
import com.urbancode.urelease.plugin.helper.*

final def workDir = new File('.').canonicalFile
def apTool = new AirPluginTool(this.args[0], this.args[1])
def props = apTool.getStepProperties();

def integrationProviderId = props['releaseIntegrationProvider'];
def releaseToken = props['releaseToken'];
def serverUrl = props['releaseServerUrl'];

final def defaultDate = "1900-01-01T12:00"


//--------------------------------------------------------------
//Authentication with Release
def releaseAuthentication (serverUrl, releaseToken) {
    Clients.loginWithToken(serverUrl, releaseToken)
}
//Authentication
releaseAuthentication (serverUrl, releaseToken)

new Change().deleteAllForIntegrationProvider(integrationProviderId)
new Initiative().deleteAllForIntegrationProvider(integrationProviderId)
def provider = new PluginIntegrationProvider().id(integrationProviderId).get()
provider.property("lastExecutionDate", defaultDate).save()

Change[] allChanges = new Change().filter("integrationProvider.id", FilterClass.UUID, FilterType.EQUALS, integrationProviderId).when().getAll()

if (allChanges.size() > 0) {
    throw new Exception("Changes could not be deleted!")
}

new Initiative().deleteAllForIntegrationProvider(integrationProviderId)

Initiative[] allInitiatives = new Initiative().filter("integrationProvider.id", FilterClass.UUID, FilterType.EQUALS, integrationProviderId).when().getAll()

if (allInitiatives.size() > 0) {
    throw new Exception("Initiatives could not be deleted!")
}

println("")
println("All changes and initiatives have been deleted successfully!")
