package org.apache.maven.model.plugin;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

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

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

import org.apache.maven.lifecycle.LifeCyclePluginAnalyzer;
import org.apache.maven.model.Build;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginContainer;
import org.apache.maven.model.PluginExecution;
import org.apache.maven.model.PluginManagement;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.apache.maven.model.building.ModelProblemCollector;
import org.apache.maven.model.building.ModelProblem.Severity;
import org.apache.maven.model.building.ModelProblem.Version;
import org.apache.maven.model.building.ModelProblemCollectorRequest;
import org.apache.maven.model.merge.MavenModelMerger;

/**
 * Handles injection of plugin executions induced by the lifecycle bindings for a packaging.
 *
 * @author Benjamin Bentmann
 */
@Named
@Singleton
public class DefaultLifecycleBindingsInjector
    implements LifecycleBindingsInjector
{

    private LifecycleBindingsMerger merger = new LifecycleBindingsMerger();

    @Inject
    private LifeCyclePluginAnalyzer lifecycle;

    public void injectLifecycleBindings( Model model, ModelBuildingRequest request, ModelProblemCollector problems )
    {
        String packaging = model.getPackaging();

        Collection<Plugin> defaultPlugins = lifecycle.getPluginsBoundByDefaultToAllLifecycles( packaging );

        if ( defaultPlugins == null )
        {
            problems.add( new ModelProblemCollectorRequest( Severity.ERROR, Version.BASE )
                    .setMessage( "Unknown packaging: " + packaging )
                    .setLocation( model.getLocation( "packaging" ) ) );
        }
        else if ( !defaultPlugins.isEmpty() )
        {
            Model lifecycleModel = new Model();
            lifecycleModel.setBuild( new Build() );
            lifecycleModel.getBuild().getPlugins().addAll( defaultPlugins );

            merger.merge( model, lifecycleModel, problems );
        }
    }

    /**
     *  The domain-specific model merger for lifecycle bindings
     */
    protected static class LifecycleBindingsMerger
        extends MavenModelMerger
    {

        private static final String PLUGIN_MANAGEMENT = "plugin-management";
        private static final String NO_VERSION_PLUGINS = "no-version-plugins";

        public void merge( Model target, Model source, ModelProblemCollector problems )
        {
            if ( target.getBuild() == null )
            {
                target.setBuild( new Build() );
            }

            Map<Object, Object> context = new HashMap<Object, Object>();
            context.put( PLUGIN_MANAGEMENT, target.getBuild().getPluginManagement() );

            mergePluginContainer_Plugins( target.getBuild(), source.getBuild(), false, context );

            @SuppressWarnings( "unchecked" )
            Collection<Plugin> defaultVersionPlugins = (Collection<Plugin>) context.get( NO_VERSION_PLUGINS );
            if ( defaultVersionPlugins != null )
            {
                List<String> plugins = new ArrayList<>( defaultVersionPlugins.size() );
                for ( Plugin p : defaultVersionPlugins )
                {
                    plugins.add( p.getArtifactId() );
                }

                problems.add( new ModelProblemCollectorRequest( Severity.WARNING, Version.BASE )
                              .setMessage( "Version not locked for default bindings plugins " + plugins
                                           + ", you should define versions in pluginManagement section of your "
                                           + "pom.xml or parent" )
                              .setLocation( target.getLocation( "packaging" ) ) );
            }
        }

        @SuppressWarnings( { "checkstyle:methodname" } )
        @Override
        protected void mergePluginContainer_Plugins( PluginContainer target, PluginContainer source,
                                                     boolean sourceDominant, Map<Object, Object> context )
        {
            List<Plugin> src = source.getPlugins();
            if ( !src.isEmpty() )
            {
                List<Plugin> tgt = target.getPlugins();

                Map<Object, Plugin> merged = new LinkedHashMap<>( ( src.size() + tgt.size() ) * 2 );

                for ( Plugin element : tgt )
                {
                    Object key = getPluginKey().apply( element );
                    merged.put( key, element );
                }

                Map<Object, Plugin> added = new LinkedHashMap<>();

                for ( Plugin element : src )
                {
                    Object key = getPluginKey().apply( element );
                    Plugin existing = merged.get( key );
                    if ( existing != null )
                    {
                        mergePlugin( existing, element, sourceDominant, context );
                    }
                    else
                    {
                        merged.put( key, element );
                        added.put( key, element );
                    }
                }

                if ( !added.isEmpty() )
                {
                    PluginManagement pluginMgmt = (PluginManagement) context.get( PLUGIN_MANAGEMENT );
                    if ( pluginMgmt != null )
                    {
                        for ( Plugin managedPlugin : pluginMgmt.getPlugins() )
                        {
                            Object key = getPluginKey().apply( managedPlugin );
                            Plugin addedPlugin = // remove plugin only if managedPlugin defines version
                                ( managedPlugin.getVersion() == null ) ? added.get( key ) : added.remove( key );
                            if ( addedPlugin != null )
                            {
                                Plugin plugin = managedPlugin.clone();
                                mergePlugin( plugin, addedPlugin, sourceDominant, Collections.emptyMap() );
                                merged.put( key, plugin );
                            }
                        }
                    }

                    if ( !added.isEmpty() )
                    {
                        // some plugins added with default version from bindings
                        context.put( NO_VERSION_PLUGINS, added.values() );
                    }
                }

                List<Plugin> result = new ArrayList<>( merged.values() );

                target.setPlugins( result );
            }
        }

        @Override
        protected void mergePluginExecution( PluginExecution target, PluginExecution source, boolean sourceDominant,
                                             Map<Object, Object> context )
        {
            super.mergePluginExecution( target, source, sourceDominant, context );

            target.setPriority( Math.min( target.getPriority(), source.getPriority() ) );
        }

    }

}

@@ -933,34 +933,8 @@
 ns;%0A
-import java.util.HashMap;%0A
 impo
@@ -3012,18 +3012,8 @@
 odel
-, problems
  );%0A
@@ -3280,87 +3280,8 @@
 nt%22;
-%0A        private static final String NO_VERSION_PLUGINS = %22no-version-plugins%22;
 %0A%0A  
@@ -3335,40 +3335,8 @@
 urce
-, ModelProblemCollector problems
  )%0A 
@@ -3511,63 +3511,65 @@
 xt =
- new HashMap%3CObject, Object%3E();%0A            context.put
+%0A                Collections.%3CObject, Object%3EsingletonMap
 ( PL
@@ -3730,942 +3730,8 @@
 t );
-%0A%0A            @SuppressWarnings( %22unchecked%22 )%0A            Collection%3CPlugin%3E defaultVersionPlugins = (Collection%3CPlugin%3E) context.get( NO_VERSION_PLUGINS );%0A            if ( defaultVersionPlugins != null )%0A            %7B%0A                List%3CString%3E plugins = new ArrayList%3C%3E( defaultVersionPlugins.size() );%0A                for ( Plugin p : defaultVersionPlugins )%0A                %7B%0A                    plugins.add( p.getArtifactId() );%0A                %7D%0A%0A                problems.add( new ModelProblemCollectorRequest( Severity.WARNING, Version.BASE )%0A                              .setMessage( %22Version not locked for default bindings plugins %22 + plugins%0A                                           + %22, you should define versions in pluginManagement section of your %22%0A                                           + %22pom.xml or parent%22 )%0A                              .setLocation( target.getLocation( %22packaging%22 ) ) );%0A            %7D
 %0A   
@@ -5569,167 +5569,17 @@
 n = 
-// remove plugin only if managedPlugin defines version%0A                                ( managedPlugin.getVersion() == null ) ? added.get( key ) : added.remove
+added.get
 ( ke
@@ -5987,253 +5987,8 @@
    %7D
-%0A%0A                    if ( !added.isEmpty() )%0A                    %7B%0A                        // some plugins added with default version from bindings%0A                        context.put( NO_VERSION_PLUGINS, added.values() );%0A                    %7D
 %0A   

Revert "[MNG-6562] added WARNING on default bindings plugins unlocked versions"