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

import java.text.DecimalFormat;
import java.util.*;


public class Topic {
    private int topicId;
    private double[][] topicLambda;

    public Topic(int topicId, double[][] topicLambda) {
        this.topicId = topicId;
        this.topicLambda = topicLambda;
    }

    public int getTopicId() {
        return topicId;
    }

    public List<Pair> getPairs() {
        double[] topicLambdaNormalized = Compute.div(topicLambda, Compute.sum(topicLambda))[0];

        ArrayList<Pair> sortedEntries = new ArrayList<Pair>();
        for (int i = 0; i < topicLambdaNormalized.length; i++) {
            sortedEntries.add(new Pair(i, topicLambdaNormalized[i]));
        }

        Collections.sort(sortedEntries, new Comparator<Pair>() {
            @Override
            public int compare(Pair o1, Pair o2) {
                return o2.value.compareTo(o1.value);
            }
        });

        return sortedEntries;
    }

    public void printPairs(cz.vutbr.feec.utko.xonder02.lda.Dictionary dictionary, int top) {
        StringBuilder builder = new StringBuilder();
        builder.append("#");
        builder.append(getTopicId());
        builder.append(": ");

        List<String> stringList = new ArrayList<String>();

        int i = 0;
        DecimalFormat decimalFormat = new DecimalFormat("#0.0000");
        for (Pair pair : getPairs()) {
            int wordId = pair.key;

            if (i++ > top) {
                break;
            }

            stringList.add(decimalFormat.format(pair.value) + "*" + dictionary.getTokenById(wordId));
        }


        builder.append(stringList.remove(0));

        for(String s : stringList) {
            builder.append(" + ");
            builder.append(s);
        }

        System.out.println(builder.toString());
    }

    class Pair {
        public Integer key;
        public Double value;

        public Pair(Integer key, Double value) {
            this.key = key;
            this.value = value;
        }
    }
}
