package com.insa.app.model;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Conversations {
    private HashMap<UUID, ObservableList<String>> conversations;

    public Conversations() {
        conversations = new HashMap<>();
    }

    public void addMessage(Message m, UUID emitterID) {
        String m_string = m.toString();
        if (conversations.containsKey(emitterID)) {
            List<String> list = conversations.get(emitterID);
            Runnable runnable = () -> {
                synchronized (list) {
                    list.add(m_string);
                }
            };
            Platform.runLater(runnable);
        } else {
            ObservableList<String> list = FXCollections.synchronizedObservableList(FXCollections.observableArrayList());
            list.add(m_string);
            Logger.getAnonymousLogger().log(Level.INFO, "Creating conversation with " + emitterID);
            conversations.put(emitterID, list);
        }
    }

    public ObservableList<String> getConversation(User user) throws RuntimeException {
        UUID id = user.getId();
        if (conversations.containsKey(id)) {
            return conversations.get(id);
        } else {
            throw new RuntimeException("No conversation found for user " + user.getName() + "["+user.getId()+"]"+"@"+user.getIpAddress());
        }
    }
}
