package org.implab.gradle.common.sources;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.gradle.api.Action;
import org.gradle.api.model.ObjectFactory;

public abstract class BuildVariantsExtension {
    private final ObjectFactory objects;
    private final Map<String, BuildVariant> variants = new HashMap<>();
    private final List<Action<? super BuildVariant>> listeners = new ArrayList<>();

    @Inject
    public BuildVariantsExtension(ObjectFactory objects) {
        this.objects = objects;
    }

    private BuildVariant newVariant(String name) {
        return objects.newInstance(BuildVariant.class, name);
    }

    public BuildVariant variant(String name, Action<? super BuildVariant> configure) {
        BuildVariant v = variants.computeIfAbsent(name, this::newVariant);
        configure.execute(v);
        for (Action<? super BuildVariant> l : listeners) {
            l.execute(v);
        }
        return v;
    }

    public void all(Action<? super BuildVariant> action) {
        variants.values().forEach(action::execute);
        listeners.add(action);
    }

    public Collection<BuildVariant> getAll() {
        return Collections.unmodifiableCollection(variants.values());
    }

    public BuildVariant getByName(String name) {
        return variants.get(name);
    }

}
