

package org.jenkinsci.plugins.credentialsbinding;

import com.cloudbees.plugins.credentials.CredentialsNameProvider;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.AbstractIdCredentialsListBoxModel;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.model.Descriptor;
import hudson.model.Item;
import hudson.security.ACL;
import hudson.util.ListBoxModel;

import java.util.Collections;

import org.kohsuke.stapler.AncestorInPath;

/**
 * Describes a {@link MultiBinding} kind.
 * @param <C> type of credentials to be bound
 */
public abstract class BindingDescriptor<C extends StandardCredentials> extends Descriptor<MultiBinding<C>> {

    protected abstract Class<C> type();

    /**
     * Determines whether this {@link MultiBinding} needs a workspace to evaluate.
     */
    public boolean requiresWorkspace() {
        return true;
    }

    public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item owner) {
        if (owner == null || !owner.hasPermission(Item.CONFIGURE)) {
            return new ListBoxModel();
        }
        // when configuring the job, you only want those credentials that are available to ACL.SYSTEM selectable
        // as we cannot select from a user's credentials unless they are the only user submitting the build
        // (which we cannot assume) thus ACL.SYSTEM is correct here.
        return new Model().withAll(CredentialsProvider.lookupCredentials(type(), owner, ACL.SYSTEM, Collections.emptyList()));
    }

    private final class Model extends AbstractIdCredentialsListBoxModel<Model,C> {

        @NonNull
        @Override
        protected String describe(@NonNull C c) {
            return CredentialsNameProvider.name(c);
        }

    }

}
