/*
 * Copyright 2010 the original author or authors.
 *
 * 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.gradle.api.publication.maven.internal.pom;

import org.apache.maven.model.Dependency;
import org.apache.maven.model.Exclusion;
import org.gradle.api.GradleException;
import org.gradle.api.artifacts.*;
import org.gradle.api.artifacts.maven.Conf2ScopeMapping;
import org.gradle.api.artifacts.maven.Conf2ScopeMappingContainer;
import org.gradle.api.publication.maven.internal.VersionRangeMapper;

import java.util.*;

class DefaultPomDependenciesConverter implements PomDependenciesConverter {
    private ExcludeRuleConverter excludeRuleConverter;
    private VersionRangeMapper versionRangeMapper;

    public DefaultPomDependenciesConverter(ExcludeRuleConverter excludeRuleConverter, VersionRangeMapper versionRangeMapper) {
        this.excludeRuleConverter = excludeRuleConverter;
        this.versionRangeMapper = versionRangeMapper;
    }

    public List<Dependency> convert(Conf2ScopeMappingContainer conf2ScopeMappingContainer, Set<Configuration> configurations) {
        Map<ModuleDependency, Set<Configuration>> dependencyToConfigurations = createDependencyToConfigurationsMap(configurations);
        Map<ModuleDependency, String> dependenciesMap = createDependencyToScopeMap(conf2ScopeMappingContainer, dependencyToConfigurations);
        List<Dependency> mavenDependencies = new ArrayList<Dependency>();
        for (ModuleDependency dependency : dependenciesMap.keySet()) {
            String scope = dependenciesMap.get(dependency);
            Set<Configuration> dependencyConfigurations = dependencyToConfigurations.get(dependency);
            if (dependency.getArtifacts().size() == 0) {
                addFromDependencyDescriptor(mavenDependencies, dependency, scope, dependencyConfigurations);
            } else {
                addFromArtifactDescriptor(mavenDependencies, dependency, scope, dependencyConfigurations);
            }
        }
        return mavenDependencies;
    }

    private Map<ModuleDependency, String> createDependencyToScopeMap(Conf2ScopeMappingContainer conf2ScopeMappingContainer,
                                                                     Map<ModuleDependency, Set<Configuration>> dependencyToConfigurations) {
        Map<ModuleDependency, String> dependencyToScope = new HashMap<ModuleDependency, String>();
        for (ModuleDependency dependency : dependencyToConfigurations.keySet()) {
            Conf2ScopeMapping conf2ScopeDependencyMapping = conf2ScopeMappingContainer.getMapping(dependencyToConfigurations.get(dependency));
            if (!useScope(conf2ScopeMappingContainer, conf2ScopeDependencyMapping)) {
                continue;
            }
            dependencyToScope.put(findDependency(dependency, conf2ScopeDependencyMapping.getConfiguration()),
                conf2ScopeDependencyMapping.getScope());
        }
        return dependencyToScope;
    }

    private ModuleDependency findDependency(ModuleDependency dependency, Configuration configuration) {
        for (ModuleDependency configurationDependency : configuration.getDependencies().withType(ModuleDependency.class)) {
            if (dependency.equals(configurationDependency)) {
                return configurationDependency;
            }
        }
        throw new GradleException("Dependency could not be found. We should never get here!");
    }

    private boolean useScope(Conf2ScopeMappingContainer conf2ScopeMappingContainer, Conf2ScopeMapping conf2ScopeMapping) {
        return conf2ScopeMapping.getScope() != null || !conf2ScopeMappingContainer.isSkipUnmappedConfs();
    }

    private Map<ModuleDependency, Set<Configuration>> createDependencyToConfigurationsMap(Set<Configuration> configurations) {
        Map<ModuleDependency, Set<Configuration>> dependencySetMap = new HashMap<ModuleDependency, Set<Configuration>>();
        for (Configuration configuration : configurations) {
            for (ModuleDependency dependency : configuration.getDependencies().withType(ModuleDependency.class)) {
                if (dependencySetMap.get(dependency) == null) {
                    dependencySetMap.put(dependency, new HashSet<Configuration>());
                }
                dependencySetMap.get(dependency).add(configuration);
            }
        }
        return dependencySetMap;
    }

    private void addFromArtifactDescriptor(List<Dependency> mavenDependencies, ModuleDependency dependency, String scope,
                                           Set<Configuration> configurations) {
        for (DependencyArtifact artifact : dependency.getArtifacts()) {
            mavenDependencies.addAll(createMavenDependenciesFromArtifactDescriptor(dependency, artifact, scope, configurations));
        }
    }

    private void addFromDependencyDescriptor(List<Dependency> mavenDependencies, ModuleDependency dependency, String scope,
                                             Set<Configuration> configurations) {
        mavenDependencies.addAll(createMavenDependenciesFromDependencyDescriptor(dependency, scope, configurations));
    }

    private List<Dependency> createMavenDependenciesFromArtifactDescriptor(ModuleDependency dependency, DependencyArtifact artifact, String scope,
                                                                           Set<Configuration> configurations) {
        return createMavenDependencies(dependency, artifact.getName(), artifact.getType(), scope, artifact.getClassifier(), configurations);
    }

    private List<Dependency> createMavenDependenciesFromDependencyDescriptor(ModuleDependency dependency, String scope, Set<Configuration> configurations) {
        return createMavenDependencies(dependency, dependency.getName(), null, scope, null, configurations);
    }

    private List<Dependency> createMavenDependencies(ModuleDependency dependency, String name, String type, String scope, String classifier,
                                                     Set<Configuration> configurations) {
        List<Dependency> mavenDependencies = new ArrayList<Dependency>();

        if (dependency instanceof ProjectDependency) {
            ProjectDependency projectDependency = (ProjectDependency) dependency;
            final String artifactId = determineProjectDependencyArtifactId((ProjectDependency) dependency);

            Configuration dependencyConfig = projectDependency.getProjectConfiguration();
            for (PublishArtifact artifactToPublish : dependencyConfig.getAllArtifacts()) {
                Dependency mavenDependency = new Dependency();
                mavenDependency.setArtifactId(artifactId);
                mavenDependency.setClassifier(artifactToPublish.getClassifier());
                mavenDependencies.add(mavenDependency);
            }
        } else {
            Dependency mavenDependency = new Dependency();
            mavenDependency.setArtifactId(name);
            mavenDependency.setClassifier(classifier);
            mavenDependencies.add(mavenDependency);
        }

        for (Dependency mavenDependency : mavenDependencies) {
            mavenDependency.setGroupId(dependency.getGroup());
            mavenDependency.setVersion(mapToMavenSyntax(dependency.getVersion()));
            mavenDependency.setType(type);
            mavenDependency.setScope(scope);
            mavenDependency.setExclusions(getExclusions(dependency, configurations));
        }

        return mavenDependencies;
    }

    private String mapToMavenSyntax(String version) {
        return versionRangeMapper.map(version);
    }

    protected String determineProjectDependencyArtifactId(ProjectDependency dependency) {
        return new ProjectDependencyArtifactIdExtractorHack(dependency).extract();
    }

    private List<Exclusion> getExclusions(ModuleDependency dependency, Set<Configuration> configurations) {
        List<Exclusion> mavenExclusions = new ArrayList<Exclusion>();
        Set<ExcludeRule> excludeRules = new HashSet<ExcludeRule>(dependency.getExcludeRules());
        for (Configuration configuration : configurations) {
            excludeRules.addAll(configuration.getExcludeRules());
        }
        for (ExcludeRule excludeRule : excludeRules) {
            Exclusion mavenExclusion = (Exclusion) excludeRuleConverter.convert(excludeRule);
            if (mavenExclusion != null) {
                mavenExclusions.add(mavenExclusion);
            }
        }
        return mavenExclusions;
    }

    public ExcludeRuleConverter getExcludeRuleConverter() {
        return excludeRuleConverter;
    }
}

@@ -7175,16 +7175,128 @@
 actId);%0A
+                if (artifactToPublish.getClassifier() != null && artifactToPublish.getClassifier() != %22%22) %7B%0A    
         
@@ -7365,24 +7365,42 @@
 ssifier());%0A
+                %7D%0A
             

Add a check for an empty or null classifier.