/*
 * File:     EAF2SMIL.java
 * Project:  MPI Linguistic Application
 * Date:     03 April 2006
 *
 * Copyright (C) 2001-2006  Max Planck Institute for Psycholinguistics
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package mpi.eudico.client.util;

import java.io.*;

import java.net.MalformedURLException;
import java.net.URL;

import java.util.Date;

import javax.xml.transform.*;
import javax.xml.transform.stream.*;


/**
 * Created on Apr 15, 2004
 * @author Alexander Klassmann
 * @version Apr 15, 2004
 */
public class EAF2SMIL {
    private static Transformer transformer2smil;
    private static Transformer transformer2rt;

    /**
     *
     * @throws TransformerException
     * @throws IOException
     */
    private static void createTransformer()
        throws TransformerException, IOException {
        if (transformer2smil == null) {
            URL eaf2smil = EAF2SMIL.class.getResource(
                    "/mpi/eudico/resources/eaf2smil.xsl");
            URL eaf2rt = EAF2SMIL.class.getResource(
                    "/mpi/eudico/resources/eaf2rt.xsl");

            TransformerFactory tFactory = TransformerFactory.newInstance();

            transformer2smil = tFactory.newTransformer(new StreamSource(
                        eaf2smil.openStream()));
            transformer2rt = tFactory.newTransformer(new StreamSource(
                        eaf2rt.openStream()));
        }
    }

    /**
     *
     * @param eafFile
     * @param smilFile
     * @param tierNames
     * @throws IOException
     * @throws TransformerException
     */
    public static void export2SMIL(File eafFile, File smilFile,
        String[] tierNames) throws IOException, TransformerException {
        export2SMIL(eafFile, smilFile, tierNames, null);
    }

    /**
     *
     * @param eafFile
     * @param smilFile
     * @param tier
     * @param mediaURL
     * @throws IOException
     * @throws TransformerException
     */
    public static void export2SMIL(File eafFile, File smilFile,
        String[] tierNames, String mediaURL)
        throws IOException, TransformerException {
        try {
            URL eafURL = new URL("file:///" + eafFile.getAbsolutePath());
            export2SMIL(eafURL, smilFile, tierNames, mediaURL);
        } catch (MalformedURLException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    /**
     *
     * @param eafURL
     * @param smilFile
     * @param tier
     * @throws IOException
     * @throws TransformerException
     */
    public static void export2SMIL(URL eafURL, File smilFile,
        String[] tierNames, String mediaURL)
        throws IOException, TransformerException {
        createTransformer();

        //Parameter setting
        String fileName = new File(eafURL.getFile()).getName();

        int index = fileName.lastIndexOf('.');
        String title = (index > 0) ? (fileName = fileName.substring(0, index))
                                   : fileName;

        String comment = "Generated from " + fileName + " on " +
            new Date(System.currentTimeMillis());

        String rtFileName = smilFile.getName();
        index = rtFileName.lastIndexOf('.');

        if (index > 0) {
            rtFileName = rtFileName.substring(0, index);
        }

        transformer2smil.setParameter("comment", comment);
        transformer2smil.setParameter("title", title);
        transformer2smil.setParameter("font_size", "3");
        transformer2rt.setParameter("font_size", "3");

        if (mediaURL != null) {
            transformer2smil.setParameter("media_url", mediaURL);
        }

        if (tierNames != null) {
            String tierString = tierNames[0];

            for (int i = 1; i < tierNames.length; i++) {
                tierString += (" " + tierNames[i]);
            }

            transformer2smil.setParameter("tier", tierString);
        }

        transformer2smil.setParameter("rtFileName", rtFileName + ".rt");

        //transformation
        transformer2smil.transform(new StreamSource(eafURL.openStream()),
            new StreamResult(smilFile));

        for (int i = 0; i < tierNames.length; i++) {
            File rtFile = new File(smilFile.getParent(),
                    rtFileName + "_" + tierNames[i] + ".rt");

            transformer2rt.setParameter("tier", tierNames[i]);

            transformer2rt.transform(new StreamSource(eafURL.openStream()),
                new StreamResult(rtFile));
        }

        //clear
        transformer2smil.clearParameters();
        transformer2rt.clearParameters();
    }

    /**
     *
     * @param eafFile
     * @param smilFile
     * @param tierNames
     * @param beginTime
     * @param endTime
     * @throws IOException
     * @throws TransformerException
     */
    public void export2SMIL(File eafFile, File smilFile, String[] tierNames,
        long beginTime, long endTime) throws IOException, TransformerException {
        export2SMIL(eafFile, smilFile, tierNames, null, beginTime, endTime);
    }

    /**
     *
     * @param eafFile
     * @param smilFile
     * @param tier
     * @param mediaURL
     * @param beginTime
     * @param endTime
     * @throws IOException
     * @throws TransformerException
     */
    public static void export2SMIL(File eafFile, File smilFile,
        String[] tierNames, String mediaURL, long beginTime, long endTime)
        throws IOException, TransformerException {
        try {
            URL eafURL = new URL("file:///" + eafFile.getAbsolutePath());
            export2SMIL(eafURL, smilFile, tierNames, mediaURL, beginTime,
                endTime);
        } catch (MalformedURLException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    /**
     *
     * @param eafURL
     * @param smilFile
     * @param tier
     * @param beginTime
     * @param endTime
     * @throws IOException
     * @throws TransformerException
     */
    public static void export2SMIL(URL eafURL, File smilFile,
        String[] tierNames, String mediaURL, long beginTime, long endTime)
        throws IOException, TransformerException {
        createTransformer();

        transformer2smil.setParameter("media_start_time", "" + beginTime);
        transformer2smil.setParameter("media_stop_time", "" + endTime);
        transformer2rt.setParameter("media_start_time", "" + beginTime);
        transformer2rt.setParameter("media_stop_time", "" + endTime);

        export2SMIL(eafURL, smilFile, tierNames, mediaURL);
    }

    public static void main(String[] args) {
        String eafFile = null;

        if (args.length > 0) {
            eafFile = args[0];

            if (eafFile.indexOf(':') == -1) {
                eafFile = "file:///" + eafFile;
            }
        }

        try {
            URL eafURL = new URL((eafFile != null) ? eafFile
                                                   : ("file:///" +
                    System.getProperty("user.dir") +
                    "/resources/testdata/elan/elan-example2.eaf"));
            export2SMIL(eafURL,
                new File(eafURL.getFile().replaceAll(".eaf$", ".smil")),
                new String[] { "W-Spch", "K-Spch" }, null, 15200, 17200);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
