package peergos.shared.user;

import jsinterop.annotations.*;

import java.util.*;

public class ServerConversation implements Comparable<ServerConversation> {

    public final long latestEpochMillis;
    @JsProperty
    public final List<ServerMessage> messages;
    public final boolean isDismissed;

    public ServerConversation(List<ServerMessage> messages) {
        this.messages = messages;
        long latest = 0;
        for (ServerMessage message : messages) {
            if (message.sentEpochMillis > latest)
                latest = message.sentEpochMillis;
        }
        ServerMessage lastMessage = messages.get(messages.size() - 1);
        this.isDismissed = lastMessage.isDismissed || lastMessage.type == ServerMessage.Type.FromUser;
        this.latestEpochMillis = latest;
    }

    @Override
    public int compareTo(ServerConversation other) {
        return Long.compare(latestEpochMillis, other.latestEpochMillis);
    }

    public static List<ServerConversation> combine(List<ServerMessage> all) {
        Map<Long, List<ServerMessage>> lookup = new HashMap<>();
        List<ServerConversation> res = new ArrayList<>();
        for (ServerMessage msg : all) {
            List<ServerMessage> conv;
            if (msg.replyToId.isPresent()) {
                lookup.putIfAbsent(msg.replyToId.get(), new ArrayList<>());
                conv = lookup.get(msg.replyToId.get());
                lookup.put(msg.id, conv);
            } else {
                conv = lookup.computeIfAbsent(msg.id, x -> new ArrayList<>());
            }
            conv.add(msg);
        }
        new HashSet<>(lookup.values()).forEach(c -> res.add(new ServerConversation(c)));
        Collections.sort(res);
        return res;
    }
}

@@ -288,22 +288,24 @@
 an isDis
-missed
+playable
 ;%0A%0A    p
@@ -672,17 +672,20 @@
 sDis
-missed
+playable
  = 
+!
 last
@@ -708,10 +708,10 @@
 sed 
-%7C%7C
+&&
  las
@@ -724,17 +724,17 @@
 ge.type 
-=
+!
 = Server

rename var