package org.academiadecodigo.bootcamp.service;

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

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

public class ServiceRegistry {
    private Map<String, Service> services;

    private static ServiceRegistry registry;

    public static ServiceRegistry getInstance() {
        if (registry == null) {
            synchronized (ServiceRegistry.class) {
                if (registry == null) {
                    registry = new ServiceRegistry();
                }
            }
        }
        return registry;
    }

    private ServiceRegistry() {
        services = new HashMap<>();
    }

    @SuppressWarnings("unchecked")
    public <T> T getService(String name) {
        System.out.println("Getting " + name + " from service registry.");
        return (T) services.get(name);
    }

    public void addService(Service service) {
        String serviceInterfaceName = service.getClass().getInterfaces()[0].getSimpleName();
        System.out.println("Adding " + serviceInterfaceName + " to service registry.");
        services.put(service.getClass().getInterfaces()[0].getSimpleName(), service);
    }
}
