/*
 * File:     LinkedFileDescriptorUtil.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.annotator.linkedmedia;

import mpi.eudico.client.annotator.commands.ELANCommandFactory;

import mpi.eudico.client.annotator.timeseries.TSTrackManager;
import mpi.eudico.client.annotator.timeseries.TimeSeriesConstants;
import mpi.eudico.client.annotator.timeseries.config.TSSourceConfiguration;
import mpi.eudico.client.annotator.timeseries.io.TSConfigurationParser;
import mpi.eudico.client.annotator.timeseries.spi.TSServiceProvider;
import mpi.eudico.client.annotator.timeseries.spi.TSServiceRegistry;

import mpi.eudico.client.annotator.util.FileExtension;
import mpi.eudico.client.annotator.util.FileUtility;

import mpi.eudico.client.annotator.viewer.TimeSeriesViewer;

import mpi.eudico.server.corpora.clomimpl.abstr.LinkedFileDescriptor;
import mpi.eudico.server.corpora.clomimpl.abstr.TranscriptionImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;


/**
 * A utility class for creating, checking and updating linked file descriptors.
 *
 * @author Han Sloetjes
 */
public class LinkedFileDescriptorUtil {
    /**
     * Creates a LinkedFileDescriptor for a file, given the path to the file.
     *
     * @param filePath the path to the file
     *
     * @return a LinkedFileDescriptor for the file
     */
    public static LinkedFileDescriptor createLFDescriptor(String filePath) {
        if ((filePath == null) || (filePath.length() == 0)) {
            return null;
        }

        String linkURL = FileUtility.pathToURLString(filePath);

        if (linkURL == null) {
            return null;
        }

        String mimeType = null;
        String extension = "";

        if (linkURL.indexOf('.') > -1) {
            extension = linkURL.substring(linkURL.lastIndexOf('.') + 1);
        }

        mimeType = mimeTypeForExtension(extension);

        LinkedFileDescriptor md = new LinkedFileDescriptor(linkURL, mimeType);

        return md;
    }

    /**
     * Returns the mime-type of a file based on its extension.
     *
     * @param extension the file extension
     *
     * @return a mime-type string, returns "unknown" when the file is not part
     *         of a  limited set of known file types in this context
     */
    public static String mimeTypeForExtension(String extension) {
        if ((extension == null) || (extension.length() < 3)) {
            return LinkedFileDescriptor.UNKNOWN_MIME_TYPE;
        }

        String lowExt = extension.toLowerCase();

        for (int i = 0; i < FileExtension.TEXT_EXT.length; i++) {
            if (lowExt.equals(FileExtension.TEXT_EXT[i])) {
                return LinkedFileDescriptor.TEXT_TYPE;
            }
        }

        for (int i = 0; i < FileExtension.LOG_EXT.length; i++) {
            if (lowExt.equals(FileExtension.LOG_EXT[i])) {
                return LinkedFileDescriptor.TEXT_TYPE;
            }
        }

        for (int i = 0; i < FileExtension.XML_EXT.length; i++) {
            if (lowExt.equals(FileExtension.XML_EXT[i])) {
                return LinkedFileDescriptor.XML_TYPE;
            }
        }

        for (int i = 0; i < FileExtension.SVG_EXT.length; i++) {
            if (lowExt.equals(FileExtension.SVG_EXT[i])) {
                return LinkedFileDescriptor.SVG_TYPE;
            }
        }

        return LinkedFileDescriptor.UNKNOWN_MIME_TYPE;
    }

    /**
     * Creates objects like viewers and updates viewer manager and layout
     * manager etc for the files linked to the transcription.
     *
     * @param transcription the Transcription
     */
    public static void initLinkedFiles(TranscriptionImpl transcription) {
        if ((transcription == null) ||
                (transcription.getLinkedFileDescriptors() == null)) {
            return;
        }

        Vector lfDescs = transcription.getLinkedFileDescriptors();
        LinkedFileDescriptor lfd;
        TSServiceRegistry registry = TSServiceRegistry.getInstance();
        TSTrackManager trackManager = null;
        ArrayList handledSources = new ArrayList();

        // first try to recreate tracks form configuration
        for (int i = 0; i < lfDescs.size(); i++) {
            lfd = (LinkedFileDescriptor) lfDescs.get(i);

            if (lfd.linkURL.endsWith(TimeSeriesConstants.CONF_SUFFIX)) {
                String path = lfd.linkURL;

                if (path.startsWith("file:")) {
                    path = path.substring(5);
                }

                TSConfigurationParser parser = new TSConfigurationParser();
                ArrayList confs = parser.parseSourceConfigs(path);

                if ((confs.size() > 0) && (trackManager == null)) {
                    trackManager = new TSTrackManager(transcription);
                    ELANCommandFactory.addTrackManager(transcription,
                        trackManager);

                    // get viewer manager, create viewer
                    TimeSeriesViewer tsViewer = ELANCommandFactory.getViewerManager(transcription)
                                                                  .createTimeSeriesViewer();
                    tsViewer.setTrackManager(trackManager);

                    // get layout manager, add viewer
                    ELANCommandFactory.getLayoutManager(transcription).add(tsViewer);
                }

                for (int j = 0; j < confs.size(); j++) {
                    TSSourceConfiguration sc = (TSSourceConfiguration) confs.get(j);
                    TSServiceProvider provider = null;

                    if (sc.getProviderClassName() != null) {
                        provider = registry.getProviderByClassName(sc.getProviderClassName());
                    }

                    if (provider == null) {
                        provider = registry.getProviderForFile(sc.getSource());
                    }

                    if (provider != null) {
                        if (!provider.isConfigurable()) {
                            provider.autoCreateTracks(sc);
                        } else {
                            provider.createTracksFromConfiguration(sc);
                        }

                        trackManager.addTrackSource(sc);
                    }

                    handledSources.add(sc.getSource());
                }
            }
        }

        for (int i = 0; i < lfDescs.size(); i++) {
            lfd = (LinkedFileDescriptor) lfDescs.get(i);

            if (handledSources.contains(lfd.linkURL)) {
                continue;
            }

            TSServiceProvider provider = registry.getProviderForFile(lfd.linkURL);

            if (provider != null) {
                if (trackManager == null) {
                    trackManager = new TSTrackManager(transcription);
                    ELANCommandFactory.addTrackManager(transcription,
                        trackManager);

                    // get viewer manager, create viewer
                    TimeSeriesViewer tsViewer = ELANCommandFactory.getViewerManager(transcription)
                                                                  .createTimeSeriesViewer();
                    tsViewer.setTrackManager(trackManager);

                    // get layout manager, add viewer
                    ELANCommandFactory.getLayoutManager(transcription).add(tsViewer);
                }

                TSSourceConfiguration config = new TSSourceConfiguration(lfd.linkURL);
                config.setProviderClassName(provider.getClass().getName());

                if (!provider.isConfigurable()) {
                    provider.autoCreateTracks(config);
                }

                trackManager.addTrackSource(config);
            }
        }
    }

    /**
     * Tries to update any object (in the viewermanager, the layoutmanager etc)
     * and finally sets the linked file descriptors in the transcription. The
     * kind of objects that have to be updated can be very diverse.
     *
     * @param transcription the Transcription with the old descriptors
     * @param descriptors the new linked file descriptors
     */
    public static void updateLinkedFiles(TranscriptionImpl transcription,
        Vector descriptors) {
        if ((transcription == null) || (descriptors == null)) {
            return;
        }

        Vector oldDescriptors = transcription.getLinkedFileDescriptors();
        List removedSources = new ArrayList(4);
        List addedSources = new ArrayList(4);

        LinkedFileDescriptor lfd;
        LinkedFileDescriptor olfd;
outerloop: 
        for (int i = 0; i < oldDescriptors.size(); i++) {
            olfd = (LinkedFileDescriptor) oldDescriptors.get(i);

            if (descriptors.size() == 0) {
                removedSources.add(olfd);
            } else {
                for (int j = 0; j < descriptors.size(); j++) {
                    lfd = (LinkedFileDescriptor) descriptors.get(j);

                    if (lfd.linkURL.equals(olfd.linkURL)) {
                        // check for changes??
                        continue outerloop;
                    }

                    if (j == (descriptors.size() - 1)) {
                        removedSources.add(olfd);
                    }
                }
            }
        }

outerloop: 
        for (int i = 0; i < descriptors.size(); i++) {
            lfd = (LinkedFileDescriptor) descriptors.get(i);

            if (oldDescriptors.size() == 0) {
                addedSources.add(lfd);
            } else {
                for (int j = 0; j < oldDescriptors.size(); j++) {
                    olfd = (LinkedFileDescriptor) oldDescriptors.get(j);

                    if (olfd.linkURL.equals(lfd.linkURL)) {
                        // check for changes??
                        continue outerloop;
                    }

                    if (j == (oldDescriptors.size() - 1)) {
                        addedSources.add(lfd);
                    }
                }
            }
        }

        // if there is any time series source detected...
        TSTrackManager trackManager = ELANCommandFactory.getTrackManager(transcription);
        TSServiceRegistry registry = TSServiceRegistry.getInstance();

        if (removedSources.size() > 0) {
            for (int i = 0; i < removedSources.size(); i++) {
                lfd = (LinkedFileDescriptor) removedSources.get(i);

                // check track manager
                if (trackManager != null) {
                    trackManager.removeTrackSource(lfd.linkURL);
                }

                // check other ??
            }
        }

        if (addedSources.size() > 0) {
            for (int i = 0; i < addedSources.size(); i++) {
                lfd = (LinkedFileDescriptor) addedSources.get(i);

                TSServiceProvider provider = registry.getProviderForFile(lfd.linkURL);

                if (provider != null) {
                    if (trackManager == null) {
                        trackManager = new TSTrackManager(transcription);
                        ELANCommandFactory.addTrackManager(transcription,
                            trackManager);

                        // get viewer manager, create viewer
                        TimeSeriesViewer tsViewer = ELANCommandFactory.getViewerManager(transcription)
                                                                      .createTimeSeriesViewer();
                        tsViewer.setTrackManager(trackManager);

                        // get layout manager, add viewer
                        ELANCommandFactory.getLayoutManager(transcription).add(tsViewer);
                    }

                    TSSourceConfiguration config = new TSSourceConfiguration(lfd.linkURL);
                    config.setProviderClassName(provider.getClass().getName());

                    if (!provider.isConfigurable()) {
                        provider.autoCreateTracks(config);
                    }

                    trackManager.addTrackSource(config);
                }
            }
        }

        // check if there are any sources left in the trackmanager? 
        // Destroy time series viewer?
        transcription.setLinkedFileDescriptors(descriptors);
        transcription.setChanged();
    }
}
