package org.RI.P1;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.tika.exception.TikaException;
import org.xml.sax.SAXException;

public class AnalyzeDirectory {
    private static List<File> files;

    private static void readFiles(String directory) throws IOException {
        files = Files.walk(Paths.get(directory)).filter(Files::isRegularFile).map(Path::toFile)
                .collect(Collectors.toList());
    }

    private static void usage() {
        System.out.println("Usage: AnalyzeDirectory <directory> <option>");
        System.out.println("option metadata: shows the filename/file type/encoding and language of the files");
        System.out.println("option links: shows all the links contained in each file");
        System.out.println("option frequency: saves word frequency to a file");
        System.exit(1);
    }

    private static void getMetadata() throws IOException, TikaException, SAXException {
        for (File file : files) {
            FileData data = new FileData(file);
            System.out.println(data);
            System.out.println("--------------------------------------------------------------------------");
        }
    }

    private static void getAllLinks() throws IOException, TikaException, SAXException {
        for (File file : files) {
            FileData data = new FileData(file);
            data.getLinks();
            System.out.println("--------------------------------------------------------------------------");
        }
    }

    private static void getWordOcurrences() throws IOException, TikaException, SAXException {
        for (File file : files) {
            FileData data = new FileData(file);
            data.setWordOcurrences();
        }
    }

    private static void chooseAction(String action) throws IOException, TikaException, SAXException {
        if (action.equals("metadata")) {
            getMetadata();
        } else if (action.equals("links")) {
            getAllLinks();
        } else if (action.equals("frequency")) {
            getWordOcurrences();
        } else {
            usage();
        }
    }

    public static void main(String[] args) throws IOException, TikaException, SAXException {
        if (args.length != 2) {
            usage();
        }
        String directory = args[0];
        String action = args[1];
        readFiles(directory);
        chooseAction(action);
    }

}
