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

import java.io.File;
import java.sql.SQLException;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.BasicConfigurator;

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

public class FileRegisterMain {
    public static void main(String[] args) {
        if (!ArgumentParser.parseArgument(args)) {
            return;
        }

        Settings settings = Settings.getInstance();

        FileRegisterDAOManager insertionDAOManager = null;
        try {
            insertionDAOManager = new FileRegisterDAOManager(settings.getDatabasePath());
            switch (settings.getListMode()) {
            case FILE_LIST:
                FileInfoRegister register = new FileInfoRegister(insertionDAOManager);
                Map<String,Set<String>> fileMap = settings.getFileMap();
                for (String domainName : fileMap.keySet()) {
                    if (!register.setDomainName(domainName)) {
                        System.err.println("Invalid domain name\t:" + domainName);
                        continue;
                    }
                    Set<String> filePathSet = fileMap.get(domainName);
                    register.registerFileSet(filePathSet);
                }
                break;
            case DIR_LIST:
                FileSearchRegister searchRegister = new FileSearchRegister(insertionDAOManager);
                for (String directoryPath : settings.getTargetDirectories()) {
                    if (!(new File(directoryPath)).canRead()) {
                        System.err.println("Invalid path: " + directoryPath);
                        continue;
                    }
                    if (!(new File(directoryPath)).isDirectory()) {
                        System.err.println("Invalid directory: " + directoryPath);
                        continue;
                    }
                    if (!searchRegister.setDomainName(directoryPath)) {
                        System.err.println("Invalid domain name\t:" + directoryPath);
                        continue;
                    }
                    searchRegister.search();
                }
                break;
            default:
                System.err.println("Nothing to DO " + settings.getListMode());
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            try {
                if (insertionDAOManager != null) {
                    insertionDAOManager.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
