/**
 *  Licensed under GPL. For more information, see
 *    http://jaxodraw.sourceforge.net/license.html
 *  or the LICENSE file in the jaxodraw distribution.
 */

package net.sf.jaxodraw.io;

import java.io.File;

import net.sf.jaxodraw.graph.JaxoGraph;
import net.sf.jaxodraw.io.exports.JaxoExportLatex;
import net.sf.jaxodraw.io.imports.JaxoImportAxodraw;
import net.sf.jaxodraw.util.JaxoLog;


/**
 * This class provides convenience methods to convert JaxoDraw
 * xml files to tex (axodraw4j) files and vice versa.
 *
 * @author Thomas Reiter
 * @since 2.0
 */
public final class JaxoCLIConvert {

    private static String destFileName(final String name, final String suffix) {
        final String result = name.substring(0, name.lastIndexOf('.') + 1) + suffix;
        JaxoLog.info(name + " ---> " + result);

        return result;
    }

    private static void toLatex(final String filename) {
        final JaxoGraph graph = new JaxoIO(null).open(new File(filename), false);

        if (graph == null) {
            JaxoLog.warn("Could not open: " + filename);
        } else {
            final JaxoExportLatex exporter = new JaxoExportLatex();
            exporter.setGraph(graph);
            exporter.export(destFileName(filename, "tex"));
        }
    }

    private static void toXML(final String filename) {
        final JaxoGraph graph = new JaxoImportAxodraw().importGraph(filename);

        if (graph == null) {
            JaxoLog.warn("Could not import: " + filename);
        } else {
            new JaxoIO(null).save(graph, "CLI convert", destFileName(filename, "xml"));
        }
    }

    /**
     * Converts an array of JaxoDraw xml files to tex files or vice versa.
     *
     * @param args an array of filenames.
     * Only Strings with the extension ".xml" or ".tex" are taken into account.
     */
    public static void convert(final String[] args) {
        for (int i = 0; i < args.length; i++) {
            final String name = args[i];

            if (name.endsWith(".xml")) {
                toLatex(name);
            } else if (name.endsWith(".tex")) {
                toXML(name);
            } else {
                JaxoLog.warn("Skipped unknown file: " + name);
            }
        }
    }

    private JaxoCLIConvert() {
        // empty
    }
}
