/*
 * File:     EAFMultipleFileUtilities.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.search.viewer;

import mpi.eudico.client.annotator.Preferences;

import mpi.eudico.client.annotator.gui.MultiFileChooser;

import mpi.eudico.client.util.DefaultFileFilter;

import mpi.search.SearchLocale;

import mpi.search.content.query.model.Constraint;
import mpi.search.content.query.model.Utilities;

import java.awt.Component;

import java.io.File;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.swing.JFileChooser;


/**
 * @author Albert Russel
 * @version Oct 27, 2004
 */
public class EAFMultipleFileUtilities {
    final static public String extension = ".eaf";

    /**
     * GUI to change content of searchDirs and searchPaths
     * @param parent parent component
     * @param searchDirs List of directories
     * @param searchPaths List of paths
     */
    static public void specifyDomain(Component parent, final List searchDirs,
        final List searchPaths) {
        MultiFileChooser chooser = new MultiFileChooser();
        chooser.setDialogTitle(SearchLocale.getString(
                "SearchDomainDialog.Title"));
        chooser.setFileFilter(new DefaultFileFilter(extension,
                "Eaf files (*." + extension + ")"));
        chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

        File lastDir = new File(System.getProperty("user.dir"));
        String dirPath = (String) Preferences.get(EAFMultipleFileSearchPanel.LAST_DIR_KEY,
                null);

        if (dirPath != null) {
            lastDir = new File(dirPath);
        }

        chooser.setCurrentDirectory(lastDir);

        // put the current search domain in the file chooser
        int nDirs = searchDirs.size();
        int nFiles = searchPaths.size();

        if ((nDirs + nFiles) > 0) {
            File[] currentFiles = new File[nDirs + nFiles];

            for (int i = 0; i < searchDirs.size(); i++) {
                currentFiles[i] = new File((String) searchDirs.get(i));
            }

            for (int i = 0; i < searchPaths.size(); i++) {
                currentFiles[i + nDirs] = new File((String) searchPaths.get(i));
            }

            chooser.setFiles(currentFiles);
        }

        // let the user choose
        int option = chooser.showDialog(parent, null);

        if (option == JFileChooser.APPROVE_OPTION) {
            // remember where we are
            String lastDirPath = chooser.getCurrentDirectory().getAbsolutePath();
            Preferences.set(EAFMultipleFileSearchPanel.LAST_DIR_KEY,
                lastDirPath, null);

            // extract search dirs and paths from chooser
            searchDirs.clear();
            searchPaths.clear();

            Object[] names = chooser.getFiles();

            for (int i = 0; i < names.length; i++) {
                String name = "" + names[i];
                File f = new File(name);

                if (f.isFile()) {
                    searchPaths.add(f.getPath());
                } else if (f.isDirectory()) {
                    searchDirs.add(f.getPath());
                }
            }

            // make the dirs and paths persistent
            Preferences.set(EAFMultipleFileSearchPanel.PREFERENCES_DIRS_KEY,
                searchDirs, null);
            Preferences.set(EAFMultipleFileSearchPanel.PREFERENCES_PATHS_KEY,
                searchPaths, null);
        }
    }

    /**
     * returns sorted list of existing and readable eaf-files
     * each file occurs only once in the list
     * @param dirs directories
     * @param paths paths
     * @return List sorted list of java.io.File's
     */
    static public File[] getUniqueEAFFilesIn(List dirs, List paths) {
        TreeSet sortedUniqueFiles = new TreeSet();

        // get the .eaf files from the directories
        for (int i = 0; i < dirs.size(); i++) {
            File dir = new File((String) dirs.get(i));

            //System.out.println(dir);
            if (dir.exists() && dir.isDirectory() && dir.canRead()) {
                sortedUniqueFiles.addAll(getAllEafFilesUnder(dir));
            }
        }

        // get the files from the paths
        for (int i = 0; i < paths.size(); i++) {
            String path = (String) paths.get(i);

            if (path.toLowerCase().endsWith(extension)) {
                File file = new File(path);

                if (file.exists() && file.canRead()) {
                    sortedUniqueFiles.add(file);
                }
            }
        }

        return (File[]) sortedUniqueFiles.toArray(new File[0]);
    }

    /**
     * returns all eaf-files (extension .eaf) in the directory
     * @param directory
     * @return List
     */
    static public List getAllEafFilesUnder(File directory) {
        List eafFiles = new ArrayList();

        File[] filesAndDirs = directory.listFiles();

        //System.out.println(filesAndDirs);
        for (int i = 0; i < filesAndDirs.length; i++) {
            File fileOrDir = filesAndDirs[i];

            if (fileOrDir.isFile() && fileOrDir.canRead()) {
                if (fileOrDir.getName().toLowerCase().endsWith(extension)) {
                    eafFiles.add(fileOrDir);
                }
            } else if (fileOrDir.isDirectory() && fileOrDir.canRead()) {
                eafFiles.addAll(getAllEafFilesUnder(fileOrDir));
            }
        }

        return eafFiles;
    }
}
