import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovy.transform.BaseScript
import groovy.util.logging.Slf4j

import org.commonjava.maven.ext.manip.model.Project
import org.apache.maven.model.Model
import org.apache.maven.model.DependencyManagement
import org.apache.maven.model.Dependency
import org.apache.maven.model.Profile;
import java.util.Properties
import java.lang.String

@BaseScript org.commonjava.maven.ext.manip.groovy.BaseScript pme

@Slf4j
public class AdjustStackProperty
{
    File basedir
    Project project

    String sv = "stack.version"

    def changeDepProp(List<Dependency> deps, String prop_value)
    {
        for (Dependency dep : deps)
        {
            String ver = dep.getVersion()
            if (ver == '${' + sv + '}')
            {
                dep.setVersion(prop_value)
            }
        }
    }

    def execute()
    {
        Model model = project.getModel();

        if (model.getGroupId() == "io.vertx" &&
            model.getArtifactId() == "vertx-dependencies")
        {
            log.info("Running vertx-dependencies fixup on {} ...", project.getKey())

            Properties prop = model.getProperties()
            if (prop.containsKey(sv))
            {
                String stack_version = prop.get(sv)
                //change all usages of that property with the actual value
                //First is there any dependencyManagment
                if (model.getDependencyManagement() != null &&
                    model.getDependencyManagement().getDependencies())
                {
                    changeDepProp(model.getDependencyManagement().getDependencies(), stack_version)
                }
                //Secondly any local dependencies
                 if (model.getDependencies())
                {
                    changeDepProp(model.getDependencies(), stack_version)
                }
            }
        }
    }
}

def AdjustStackProperty a = new AdjustStackProperty(basedir:pme.getBaseDir(), project:pme.getProject())
a.execute()
