package com.thalesgroup.nl.chat.impl;

import com.thalesgroup.nl.chat.api.Chat;
import org.osgi.service.component.annotations.*;

import java.util.HashMap;
import java.util.Map;

@Component(
        property = {
                "osgi.command.scope=chat",
                "osgi.command.function=send"
        },
        immediate = true,
        service = Object.class
)
public class ChatServer {
    public static final String NAME = "Bas";
    private Map<String, Chat> chatters = new HashMap<>();
    @Activate
    public ChatServer() {

    }

    @Reference(policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE)
    public void addChatter(Chat chat, Map props){
        String name = (String) props.get("participant.name");
        System.out.printf("Adding %s%n", name);
        chatters.put(name, chat);
        chat.sendMessage(NAME, String.format("Hoi %s!", name));
    }
    
    public void removeChatter(Chat chat, Map props){
        String name = (String) props.get("participant.name");
        System.out.printf("Removing %s%n", name);
        chatters.remove(name);
    }

    public void send(String name, String message){
        Chat chat = chatters.get(name);
        if(chat == null){
            System.out.printf("Error: %s not found%n", name);
        } else {
            chat.sendMessage(NAME, message);
        }
    }

    @Deactivate
    public void deactivate(){

    }
}
