/*
 * Copyright 2010 SpringSource
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.build.osgi.validator;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.Path;

public final class BundleResolutionValidatorTask {

    private Path bundlePath;

    private Path equinoxPath;

    private Path supportingBundlesPath;

    public void setBundlePath(Path bundlePath) {
        this.bundlePath = bundlePath;
    }

    public void addEquinoxPath(Path path) {
        this.equinoxPath = path;
    }

    public void addSupportingBundlesPath(Path path) {
        this.supportingBundlesPath = path;
    }

    public void execute() throws BuildException {
        init();
        try {
            new BundleResolutionValidator(getBundle(this.bundlePath), getBundles(this.supportingBundlesPath), getBundle(this.equinoxPath)).validate();
        } catch (ValidationFailedException e) {
            throw new BuildException("Validation failed", e);
        }
    }

    private void init() throws BuildException {
        if (bundlePath == null) {
            throw new BuildException("'bundlePath' must be set");
        }

        if (equinoxPath == null) {
            throw new BuildException("'equinoxPath' must be set");
        }

        if (supportingBundlesPath == null) {
            throw new BuildException("'supportingBundlesPath' must be set");
        }
    }

    private File getBundle(Path path) {
        return new File(path.list()[0]);
    }

    private List<File> getBundles(Path path) {
        String[] pathEntries = path.list();
        List<File> bundleFiles = new ArrayList<File>(pathEntries.length);

        for (String pathEntry : pathEntries) {
            bundleFiles.add(new File(pathEntry));
        }

        return bundleFiles;
    }
}