/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2012, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.as.config.assembly;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.jboss.as.config.assembly.ModuleParser.ModuleDependency;
import org.jboss.logging.Logger;
import org.jboss.modules.ModuleIdentifier;

/**
 * Generate module directory pattern file as used by FileSet.includes
 * file http://ant.apache.org/manual/Types/fileset.html
 *
 * @author Thomas.Diesler@jboss.com
 * @since 06-Sep-2012
 */
public class GenerateModulesDefinition {

    static Logger log = Logger.getLogger(GenerateModulesDefinition.class);

    static final String SPLIT_PATTERN = ",(\\s*)";
    static final String SKIP_SUBSYSTEMS = "skip-subsystems";
    static final String NO_MODULE_DEPENENCIES = "no-module-dependencies";

    private final File inputFile;
    private final String profile;
    private final File resourcesDir;
    private final File modulesDir;
    private final String[] staticModules;
    private final File outputFile;

    /**
     * arg[0] - subsystems definition file as generated by {@link GenerateSubsystemsDefinition}
     * arg[1] - subsytem profile (e.g. default)
     * arg[2] - resources directory for server definitions (e.g. wildfly/build/src/main/resources)
     * arg[3] - modules directory for server definitions (e.g. wildfly/build/target/wildfly-8.0.0/modules)
     * arg[4] - a comma seperated list of modules to include (e.g. org.jboss.as.standalone,org.jboss.as.console)
     * arg[5] - the output file (e.g. target/module-dependencies.txt)
     */
    public static void main(String[] args) throws Exception {
        if (args == null)
            throw new IllegalArgumentException("Null args");
        if (args.length < 6)
            throw new IllegalArgumentException("Invalid args: " + Arrays.asList(args));

        int index = 0;
        if (args[index] == null || args[index].isEmpty()) {
            throw new IllegalArgumentException("No input file");
        }
        File inputFile = new File(args[index++]);

        if (args[index] == null) {
            throw new IllegalArgumentException("No profile");
        }
        String profile = args[index++];

        if (args[index] == null || args[index].isEmpty()) {
            throw new IllegalArgumentException("No resources dir");
        }
        File resourcesDir = new File(args[index++]);

        if (args[index] == null || args[index].isEmpty()) {
            throw new IllegalArgumentException("No modules dir");
        }
        File modulesDir = new File(args[index++]);

        String[] staticModules = new String[] {};
        if (args[index] != null && !args[index].isEmpty()) {
            staticModules = args[index].trim().split(SPLIT_PATTERN);
        }
        index++;

        if (args[index] == null || args[index].isEmpty()) {
            throw new IllegalArgumentException("No output file");
        }
        File outputFile = new File(args[index]);

        new GenerateModulesDefinition(inputFile, profile, resourcesDir, modulesDir, staticModules, outputFile).process();
    }

    private GenerateModulesDefinition(File inputFile, String profile, File resourcesDir, File modulesDir, String[] staticModules, File outputFile) {
        this.inputFile = inputFile;
        this.profile = profile;
        this.resourcesDir = resourcesDir;
        this.modulesDir = modulesDir;
        this.staticModules = staticModules;
        this.outputFile = outputFile;
    }

    private void process() throws XMLStreamException, IOException {

        ElementNode modulesNode = new ElementNode(null, "modules", "urn:modules:1.0");
        List<ModuleIdentifier> dependencies = new ArrayList<ModuleIdentifier>();

        if (!inputFile.getName().equals(SKIP_SUBSYSTEMS)) {
            SubsystemsParser parser = new SubsystemsParser(inputFile);
            parser.parse();

            for (SubsystemConfig config : parser.getSubsystemConfigs().get(profile)) {
                File configFile = new File(resourcesDir + File.separator + config.getSubsystem());
                SubsystemParser configParser = new SubsystemParser(null, config.getSupplement(), configFile);
                configParser.parse();

                ModuleIdentifier moduleId = ModuleIdentifier.create(configParser.getExtensionModule());
                processModuleDependency(dependencies, modulesNode, new ModuleDependency(moduleId, false));
            }
        }

        for (String staticId : staticModules) {
            if (!staticId.isEmpty()) {
                ModuleIdentifier moduleId = ModuleIdentifier.fromString(staticId);
                processModuleDependency(dependencies, modulesNode, new ModuleDependency(moduleId, false));
            }
        }

        // sort the dependencies
        Comparator<ModuleIdentifier> comp = new Comparator<ModuleIdentifier>() {
            @Override
            public int compare(ModuleIdentifier o1, ModuleIdentifier o2) {
                return o1.toString().compareTo(o2.toString());
            }
        };
        Collections.sort(dependencies, comp);

        PrintWriter pw = new PrintWriter(new FileWriter(outputFile));
        try {
            if (!dependencies.isEmpty()) {
                for (ModuleIdentifier moduleId : dependencies) {
                    String path = moduleId.getName().replace('.', '/') + '/' + moduleId.getSlot();
                    pw.println(path + '/' + "**");
                }
            } else {
                pw.println(NO_MODULE_DEPENENCIES);
            }
        } finally {
            pw.close();
        }

        String xmloutput = outputFile.getPath();
        Writer writer = new FileWriter(xmloutput.substring(0, xmloutput.lastIndexOf(".")) + ".xml");
        try {
            XMLOutputFactory factory = XMLOutputFactory.newInstance();
            XMLStreamWriter xmlwriter = new FormattingXMLStreamWriter(factory.createXMLStreamWriter(writer));
            modulesNode.marshall(xmlwriter);
        } finally {
            writer.close();
        }
    }

    private void processModuleDependency(List<ModuleIdentifier> dependencies, ElementNode parentNode, ModuleDependency dep) throws IOException, XMLStreamException {
        ModuleIdentifier moduleId = dep.getModuleId();
        if (dependencies.contains(moduleId)) {
            log.debugf("Already defined: %s", moduleId);
            return;
        }

        ElementNode moduleNode = new ElementNode(parentNode, "module");
        moduleNode.addAttribute("name", new AttributeValue(moduleId.toString()));
        parentNode.addChild(moduleNode);

        if (!dep.isOptional()) {
            dependencies.add(moduleId);

            String path = moduleId.getName().replace('.', '/') + '/' + moduleId.getSlot();
            String modulespath = "system" + File.separator + "layers" + File.separator + "base";
            File moduleFile = new File(modulesDir + File.separator + modulespath + File.separator + path + File.separator + "module.xml");

            ModuleParser moduleParser = new ModuleParser(moduleFile);
            moduleParser.parse();

            List<ModuleDependency> moduledeps = moduleParser.getDependencies();
            for (ModuleDependency aux : moduledeps) {
                processModuleDependency(dependencies, moduleNode, aux);
            }
        } else {
            moduleNode.addAttribute("optional", new AttributeValue("true"));
        }
    }
}
