001/*
002 * SPDX-License-Identifier: Apache-2.0
003 *
004 * Copyright 2025-2026 The Enola <https://enola.dev> Authors
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 *     https://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package dev.enola.chat;
019
020import com.google.errorprone.annotations.ThreadSafe;
021
022import dev.enola.common.context.TLC;
023import dev.enola.data.id.MultibaseIRI;
024import dev.enola.identity.SubjectContextKey;
025
026import java.time.Instant;
027import java.util.Queue;
028import java.util.concurrent.ConcurrentLinkedQueue;
029import java.util.function.Consumer;
030
031@ThreadSafe
032public class SimpleInMemorySwitchboard implements Switchboard {
033
034    private final Queue<Consumer<Message>> consumers = new ConcurrentLinkedQueue<>();
035    final Queue<Message> messages = new ConcurrentLinkedQueue<>();
036
037    @Override
038    public synchronized void post(Message.Builder builder) {
039        if (builder.id() == null) builder.id(MultibaseIRI.random());
040        if (builder.from() == null) builder.from(TLC.get(SubjectContextKey.USER));
041        if (builder.createdAt() == null) builder.createdAt(Instant.now());
042        if (builder.modifiedAt() == null) builder.modifiedAt(builder.createdAt());
043        var message = builder.build();
044        messages.add(message);
045
046        // TODO: Accept Messages in a separate new thread per Consumer
047        consumers.forEach(c -> c.accept(message));
048    }
049
050    @Override
051    public synchronized void watch(Consumer<Message> consumer) {
052        messages.forEach(consumer);
053        consumers.add(consumer);
054    }
055}