package dp.kotul.bamboospecsapplication.creator;

import com.atlassian.bamboo.specs.api.builders.Variable;
import dp.kotul.bamboospecsapplication.EnvironmentEnum;
import dp.kotul.bamboospecsapplication.configuration.DeploymentConfiguration;
import dp.kotul.bamboospecsapplication.configuration.EnvironmentVariable;
import dp.kotul.bamboospecsapplication.configuration.Mount;
import dp.kotul.bamboospecsapplication.configuration.Port;
import dp.kotul.bamboospecsapplication.util.BambooUtils;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.List;

public class DeploymentVariableCreator {
    private DeploymentVariableCreator(){}

    public static Variable[] createVariables(EnvironmentEnum environment, DeploymentConfiguration deployment) {
        List<Variable> variables = new ArrayList<>();

        for(Port port: deployment.getPorts()) {
            variables.add(new Variable("host" + port.getName(), port.getHost()));
            variables.add(new Variable("container" + port.getName(), port.getContainer()));
        }

        for (Mount mount: deployment.getMounts()) {
            variables.add(new Variable("host" + mount.getName(), mount.getHostPath()));
            variables.add(new Variable("container" + mount.getName(), mount.getContainerPath()));
        }

        for (EnvironmentVariable var: deployment.getEnvironmentVariables()) {
            String value = var.getValue() != null ? var.getValue() : getVariableForEnvironment(var, environment);
            if (value == null) {
                continue;
            }
            variables.add(new Variable(var.getName(), BambooUtils.replaceEnvPlaceholderWithEnvironment(value, environment)));
        }

        return variables.stream().toArray(Variable[]::new);
    }

    private static String getVariableForEnvironment(EnvironmentVariable envVar, EnvironmentEnum environment) {
        switch (environment) {
            case DEV: return envVar.getDevValue();
            case STAGE: return envVar.getStageValue();
            case PROD: return envVar.getProdValue();
            default: throw new InvalidParameterException("Environment " + environment.name() + " is not supported");
        }
    }
}
