package org.texttechnologylab.project.gruppe_05_1.domain.nlp;

import org.bson.Document;

import java.util.*;
import java.util.stream.Collectors;

public class Topic {
    String      topic;
    Double      score;
    String      text;

    public Topic() {
    }

    public Topic(String topic, Double score, String text) {
        this.topic = topic;
        this.score = score;
        this.text = text;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public Double getScore() {
        return score;
    }

    public void setScore(Double score) {
        this.score = score;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Topic topic1)) return false;
        return Double.compare(score, topic1.score) == 0 && Objects.equals(topic, topic1.topic) && Objects.equals(text, topic1.text);
    }

    @Override
    public int hashCode() {
        return Objects.hash(topic, score, text);
    }

    @Override
    public String toString() {
        return new StringJoiner(", ", Topic.class.getSimpleName() + "[", "]")
                .add("topic='" + topic + "'")
                .add("score=" + score)
                .add("text='" + text + "'")
                .toString();
    }


    /**
     * Die Topics-Dokumente (Speech --> analysisResults --> topics) aus der MongoDB lesen
     * @param topicsDocs Eine Liste von Mongo-Dokumenten
     * @return Eine Liste der Topics
     */
    public static List<Topic> readTopicsFromMongo(List<Document> topicsDocs) {
        List<Topic> topics = new ArrayList<>();
        for (Document doc : topicsDocs) {
            topics.add(new Topic(doc.getString("topic"),
                                 doc.getDouble("score"),
                                 doc.getString("text")
                    ));
        }
        return topics;
    }


    /**
     * Topic-Informationen "verdichten":
     * Ausgangssituation: eine Liste mit mehreren Topics. Ein Topic kann in dieser Liste mehrfach vorkommen.
     * Man will wissen, welche Score hat jeden Topic. Hier werden die Werte der jeweiligen Topics summiert.
     *
     * @param topicsList
     * @return Map<String, Double>
     */
    public static Map<String, Double> condenseTopicInformation(List<Topic> topicsList) {
        Map<String, Double> condensedTopicInfo = new HashMap<>();

        for (Topic t : topicsList) {
            Double oldValue = condensedTopicInfo.get(t.getTopic());
            if (oldValue != null) {
                condensedTopicInfo.replace(t.getTopic(), oldValue + t.getScore());
            } else {
                condensedTopicInfo.put(t.getTopic(), t.getScore());
            }
        }

        return condensedTopicInfo;
    }
}
