package com.tikal.jenkins.plugins.multijob;

import hudson.EnvVars;
import hudson.Extension;
import hudson.model.*;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Restricted(NoExternalUse.class)
public class MultiJobParametersAction extends ParametersAction {

    private List<ParameterValue> parameters;

    public MultiJobParametersAction(@Nonnull List<ParameterValue> parameters) {
        super(parameters);
        this.parameters = parameters;
    }

    public MultiJobParametersAction(ParameterValue... parameters) {
        this(Arrays.asList(parameters));
    }

    private Object readResolve() {
        List<ParameterValue> superParameters = super.getParameters();
        // Migrate the stuf if there is inconsistency
        if (!parameters.isEmpty() && (superParameters == null || superParameters.isEmpty())) {
            // TODO: Should it actually check if the lists are diffrerent?
            // No use-case exception reflection/groovy
            return new MultiJobParametersAction(parameters);
        }
        return this;
    }
    
    @Override
    public List<ParameterValue> getParameters() {
        return Collections.unmodifiableList(parameters);
    }

    @Override
    public ParameterValue getParameter(String name) {
        for (ParameterValue parameter : parameters) {
            if (parameter != null && parameter.getName().equals(name)) {
                return parameter;
            }
        }

        return null;
    }

    @Extension
    public static final class MultiJobParametersActionEnvironmentContributor extends EnvironmentContributor {

        @Override
        public void buildEnvironmentFor(@Nonnull Run r, @Nonnull EnvVars envs, @Nonnull TaskListener listener) throws IOException, InterruptedException {
            MultiJobParametersAction action = r.getAction(MultiJobParametersAction.class);
            if (action != null) {
                for (ParameterValue p : action.getParameters()) {
                    envs.putIfNotNull(p.getName(), String.valueOf(p.getValue()));
                }
            }
        }
    }
}

@@ -759,495 +759,8 @@
  %7D%0A%0A
-    private Object readResolve() %7B%0A        List%3CParameterValue%3E superParameters = super.getParameters();%0A        // Migrate the stuf if there is inconsistency%0A        if (!parameters.isEmpty() && (superParameters == null %7C%7C superParameters.isEmpty())) %7B%0A            // TODO: Should it actually check if the lists are diffrerent?%0A            // No use-case exception reflection/groovy%0A            return new MultiJobParametersAction(parameters);%0A        %7D%0A        return this;%0A    %7D%0A    %0A
     

Revert "[JENKINS-38850] - Add migration logic for actions loaded from the disk"