/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2014. 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

import java.text.SimpleDateFormat

import com.urbancode.commons.util.query.QueryFilter.FilterType;
import com.urbancode.release.rest.framework.QueryParams.FilterClass;
import com.urbancode.release.rest.models.Release;
import com.urbancode.release.rest.models.internal.Phase;
import com.urbancode.release.rest.models.internal.ReleaseEnvironment;
import com.urbancode.release.rest.models.internal.ScheduledDeployment;
import com.urbancode.release.rest.models.internal.DeploymentPlan;
import com.urbancode.release.rest.models.internal.PluginIntegrationProvider;
import com.urbancode.air.CRMapper;

public class FetchIntegrationHelper {

    private PluginIntegrationProvider integration

    public FetchIntegrationHelper(PluginIntegrationProvider integration) {
        this.integration = integration
    }

    public def shouldCreateDeployment(ticket, releaseField, envField, state, defaultEnv) {
        def hasRequiredFields = false
        if(ticket[releaseField] != null && ticket[releaseField] != "") {
            // Does this have a default env or a specified env?
            if(defaultEnv != null && defaultEnv != "") {
                hasRequiredFields = true
            } else if (ticket[envField] != null && ticket[envField] != "") {
                hasRequiredFields = true
            }
        }

        def isProperState = false
        if(state == ticket.state) {
            isProperState = true
        }

        def isAlreadyCreated = false
        CRMapper mapper = new CRMapper(integration);


        def sdId = mapper.getSDForCR(ticket.number);

        isAlreadyCreated = (sdId != null)

        return hasRequiredFields && isProperState && !isAlreadyCreated;
    }

    public def createScheduledDeployment(releaseName, environmentName, scheduledTimestamp, crId, defaultEnv) {

        def envName = environmentName;
        if (envName == null || envName == '') {
            envName = defaultEnv
            println "Using Default Env: " + defaultEnv
        }

        def release = getReleaseByName(releaseName);

        // println release

        Phase[] phases = release.phases;

        def phaseId = null
        def envId = null
        def deploymentPlanId = null

        phases.each{ phase ->
            ReleaseEnvironment[] envs = phase.environments;

            envs.each { env ->

                if(env.name.equals(envName)) {
                    phaseId = phase.id
                    envId = env.id
                    deploymentPlanId = phase.deploymentPlan.id
                }

            }
        }

        def timestamp = new Date().getTime();
        if(scheduledTimestamp != null && scheduledTimestamp != '') {
            timestamp = new DateParser().parseDate(scheduledTimestamp).getTime()
        }

        ScheduledDeployment sd = new ScheduledDeployment()

        sd = sd.release(release)
                .phase(new Phase().id(phaseId))
                .environment(new ReleaseEnvironment().id(envId))
                .deploymentPlan(new DeploymentPlan().id(deploymentPlanId))
                .scheduledDate(timestamp).save();

        CRMapper mapper = new CRMapper(integration);
        mapper.addRecord(sd.id, crId)
    }

    private def getReleaseByName(releaseName) {
        Release query = new Release();
        query.filter("name", FilterClass.STRING, FilterType.EQUALS, releaseName);
        query.format("detail")

        Release[] result = query.getAll()

        if (result.size() > 1) {
            println "Found more than one release named: " + releaseName
        } else if (result.size() == 0) {
            println "Found no release named: " + releaseName
        } else {
            return result[0]
        }

        return null
    }

    private def addNewDeploymentToIntegration(sdId) {

    }
}