package cz.vutbr.feec.utko.xonder02.lda;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;

public class Document implements Iterable<Term> {
    private LinkedList<Term> terms = new LinkedList<Term>();
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void putTerm(Term term) {
        terms.push(term);
    }

    public Iterator<Term> iterator() {
        return terms.iterator();
    }

    public int[] getTermIds() {
        int[] output = new int[terms.size()];

        int i = 0;
        for (Term term : terms) {
            output[i++] = term.id;
        }

        return output;
    }

    public double[] getFrequencies() {
        double[] output = new double[terms.size()];

        int i = 0;
        for (Term term : terms) {
            output[i++] = term.frequency;
        }

        return output;
    }

    public int getTermCount() {
        return terms.size();
    }

    public static Document generate(String[] tokens, Dictionary dictionary, boolean removeNotExistsTokens) {
        HashMap<String, Integer> frequencies = new HashMap<String, Integer>();

        for (String token : tokens) {
            if (frequencies.containsKey(token)) {
                frequencies.put(token, frequencies.get(token) + 1);
            } else {
                frequencies.put(token, 1);
            }
        }

        Document document = new Document();

        for (String token : frequencies.keySet()) {
            if (removeNotExistsTokens && !dictionary.tokenExists(token)) {
                dictionary.putNotExistsToken(token);
                continue;
            }

            int tokenId = dictionary.putToken(token);

            Term term = new Term(tokenId, frequencies.get(token));
            document.putTerm(term);
        }

        return document;
    }
}
