package tsp.application;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Scanner;

public class Document {

    private String content;
    HashMap<String, Double> frequencies;


    public Document(String text){
        this.content = text;
        this.frequencies = new HashMap<>();
        this.addFrequencies();
    }

    public static Document fromURL(String url){
        String content = readStringFromURL(url);
        return new Document(content);
    }

    public static Document fromFile(String filename){
        String content = readFile(filename);
        return new Document(content);
    }

    private static String readFile(String filename){
        String content = "";
        try {
            content = new String(Files.readAllBytes(Paths.get(filename)));
        } catch (IOException e) {
            System.err.println("The file " + filename + " does not exist");
            content = "";
        }
        return content;
    }

    public static String readStringFromURL(String requestURL)
    {
        try {
            Files.createDirectories(Paths.get("cache_documents/"));
        } catch (IOException e) {
            System.err.println("Problem while creating the cache file...");
        }
        String[] filenameSplit = requestURL.split("/");
        String filename = "cache_documents/" + filenameSplit[filenameSplit.length - 1];
        File f = new File(filename);
        if(f.exists() && !f.isDirectory()) {
            return readFile(filename);
        }
        String res = "";
        try (Scanner scanner = new Scanner(new URL(requestURL).openStream(),
                StandardCharsets.UTF_8))
        {
            scanner.useDelimiter("\\A");
            res = scanner.hasNext() ? scanner.next() : "";
        } catch (MalformedURLException e) {
            System.err.println("Misformed URL");
        } catch (IOException e) {
            System.err.println("Error Reading URL");
        }
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(filename, true));
            writer.write(res);
            writer.close();
        } catch (IOException e) {
            System.err.println("Problem saving to cache...");
        }
        return res;
    }

    public String[] preprocess(){
        content = content.toLowerCase();
        return content.split("[ \n]");
    }

    private void addFrequencies(){
        String[] words = this.preprocess();
        for (String word: words){
            if (!frequencies.containsKey(word)){
                frequencies.put(word, 0.0);
            }
            frequencies.put(word, frequencies.get(word) + 1.0 / words.length);
        }
    }

    public double getFrequency(String word){
        if (!this.frequencies.containsKey(word)) return 0;
        return this.frequencies.get(word);
    }

    @Override
    public String toString() {
        return this.content.split("\n")[0];
    }

}
