/*
 * JBoss, Home of Professional Open Source
 * Copyright 2012, Red Hat Middleware LLC, and individual contributors
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * 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.wildfly.swarm.arquillian.daemon.protocol;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

import org.jboss.arquillian.container.test.spi.TestDeployment;
import org.jboss.arquillian.container.test.spi.client.deployment.DeploymentPackager;
import org.jboss.arquillian.container.test.spi.client.deployment.ProtocolArchiveProcessor;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ArchivePath;
import org.jboss.shrinkwrap.api.Filter;
import org.jboss.shrinkwrap.api.Node;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.impl.base.asset.ServiceProviderAsset;

/**
 * {@link DeploymentPackager} to merge auxiliar archive contents with the archive provided by the user
 *
 * @author <a href="mailto:alr@jboss.org">Andrew Lee Rubinger</a>
 * @author Toby Crawley
 */
public enum DaemonDeploymentPackager implements DeploymentPackager {

    INSTANCE;

    private static final Logger log = Logger.getLogger(DaemonDeploymentPackager.class.getName());

    @Override
    public Archive<?> generateDeployment(final TestDeployment testDeployment,
        final Collection<ProtocolArchiveProcessor> processors) {
        // Merge auxiliary archives with the declared for ARQ and testrunner support
        final JavaArchive archive = testDeployment.getApplicationArchive().as(JavaArchive.class);
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Archive before additional packaging: " + archive.toString(true));
        }
        final Map<ArchivePath, List<Node>> serviceDescriptors = new HashMap<>();
        findServiceDescriptors(archive, serviceDescriptors);
        testDeployment.getAuxiliaryArchives().forEach(aux -> {
            findServiceDescriptors(aux, serviceDescriptors);
            archive.merge(aux);
        });

        mergeServiceDescriptors(serviceDescriptors)
                .forEach((path, asset) -> archive.add(asset, path));

        if (log.isLoggable(Level.FINEST)) {
            log.finest("Archive after additional packaging: " + archive.toString(true));
        }

        return archive;
    }

    private Map<ArchivePath, Asset> mergeServiceDescriptors(Map<ArchivePath, List<Node>> descs) {
        return descs.entrySet()
                .stream()
                .collect(Collectors.toMap(Map.Entry::getKey,
                                          entry -> mergeServiceDescriptors(entry.getValue())));
    }

    private Asset mergeServiceDescriptors(List<Node> descs) {
        final List<String> lines = new ArrayList<>();
        descs.forEach(n -> {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(n.getAsset().openStream())) ) {
                String line;
                while ((line = in.readLine()) != null) {
                    lines.add(line);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        return new ServiceProviderAsset(lines.toArray(new String[lines.size()]));
    }

    private void findServiceDescriptors(Archive<?> archive, Map<ArchivePath, List<Node>> descs) {
        archive.getContent(path -> path.get().startsWith("/META-INF/services/"))
                .forEach((path, node) -> {
                    List<Node> nodes = descs.get(path);
                    if (nodes == null) {
                        nodes = new ArrayList<>();
                        descs.put(path, nodes);
                    }
                    nodes.add(node);
                });
    }
}

@@ -1156,16 +1156,86 @@
 ctors;%0A%0A
+import org.jboss.arquillian.container.spi.client.deployment.Validate;%0A
 import o
@@ -1674,16 +1674,132 @@
 .Asset;%0A
+import org.jboss.shrinkwrap.api.container.LibraryContainer;%0Aimport org.jboss.shrinkwrap.api.container.WebContainer;%0A
 import o
@@ -1832,32 +1832,81 @@
 ec.JavaArchive;%0A
+import org.jboss.shrinkwrap.api.spec.WebArchive;%0A
 import org.jboss
@@ -2600,20 +2600,16 @@
   final 
-Java
 Archive 
@@ -2660,30 +2660,8 @@
 ve()
-.as(JavaArchive.class)
 ;%0A  
@@ -2794,32 +2794,556 @@
 ue));%0A        %7D%0A
+        if (Validate.isArchiveOfType(WebArchive.class, archive)) %7B%0A            ((LibraryContainer%3C?%3E)archive).addAsLibraries(testDeployment.getAuxiliaryArchives());%0A        %7D else %7B%0A            mergeAuxAsClasses(archive, testDeployment);%0A        %7D%0A%0A        if (log.isLoggable(Level.FINEST)) %7B%0A            log.finest(%22Archive after additional packaging: %22 + archive.toString(true));%0A        %7D%0A%0A        return archive;%0A    %7D%0A%0A    private void mergeAuxAsClasses(final Archive%3C?%3E archive, final TestDeployment testDeployment) %7B%0A
         final Ma
@@ -3763,176 +3763,8 @@
 );%0A%0A
-        if (log.isLoggable(Level.FINEST)) %7B%0A            log.finest(%22Archive after additional packaging: %22 + archive.toString(true));%0A        %7D%0A%0A        return archive;%0A
     
@@ -3826,16 +3826,22 @@
 riptors(
+final 
 Map%3CArch
@@ -4134,16 +4134,22 @@
 riptors(
+final 
 List%3CNod
@@ -4735,16 +4735,22 @@
 riptors(
+final 
 Archive%3C
@@ -4760,16 +4760,22 @@
 archive,
+ final
  Map%3CArc

Add auxiliary jars as libs to wars [SWARM-138]