package jp.ac.osaka_u.ist.sel.similarity.register;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

import jp.ac.osaka_u.ist.sel.similarity.commons.FileSearch;
import jp.ac.osaka_u.ist.sel.similarity.commons.Settings;
import jp.ac.osaka_u.ist.sel.similarity.commons.SupportedLanguage;
import jp.ac.osaka_u.ist.sel.similarity.register.database.FileRegisterDAOManager;

/**
 * Search files and register information of them into the database.
 * 
 * @author ysk-ssk
 *
 */
public class FileSearchRegister extends FileInfoRegister {
    private FileSearch _searcher;
    private Set<String> _extensions;

    /**
     * 
     * @param daoManager
     * @throws SQLException
     * @throws IOException
     */
    public FileSearchRegister(FileRegisterDAOManager daoManager) throws SQLException, IOException {
        super(daoManager);
        // search initialization
        _searcher = new FileSearch();
        // set extensions for target languages
        _extensions = new HashSet<String>();
        Set<String> languages = Settings.getInstance().getTargetLanguages();
        for (String lang : languages) {
            // extensions for the target language
            Set<String> extensions = SupportedLanguage.getTargetExtensionSet(lang);
            _extensions.addAll(extensions);
        }
    }

    public void search() throws IOException, SQLException {
        // register the base path of the application
        registerNewDomain();

        File[] files = null;
        String targetRegix = "";
        int i = 0;
        if (Settings.getInstance().isDetectAll()) {
            targetRegix = "*";
        } else {
            for (String ext : _extensions) {
                if (i++ > 0) {
                    targetRegix += "|";
                }
                targetRegix += "*." + ext + "$";
            }
        }
        try {
            _searcher.clear();
            files = _searcher.listFiles(_domainName, targetRegix);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return;
        }
        if (files.length <= 0) {
            return;
        }
        // register files
        for (File file : files) {
            String ext = SupportedLanguage.getFileExtension(file.getName());
            registerFile(file, ext);
        }
    }

}
