package com.axis.innovators.box.browser;

import java.util.Map;
import java.util.concurrent.*;
import java.util.function.Consumer;

public class WindowRegistry {
    private static WindowRegistry instance;
    private final ConcurrentMap<String, BrowserWindow> windows =
            new ConcurrentHashMap<>();
    private final Map<String, Consumer<String>> callbacks = new ConcurrentHashMap<>();

    private WindowRegistry() {}

    public static synchronized WindowRegistry getInstance() {
        if (instance == null) {
            instance = new WindowRegistry();
        }
        return instance;
    }

    public void registerWindow(BrowserWindow window) {
        windows.put(window.getWindowId(), window);
    }

    public void registerCallback(String requestId, Consumer<String> handler) {
        callbacks.put(requestId, handler);
    }

    public Consumer<String> getCallback(String requestId) {
        return callbacks.remove(requestId);
    }

    public void unregisterWindow(String windowId) {
        BrowserWindow window = windows.remove(windowId);
        if (window != null) {
            window.closeWindow();
        }
    }

    public BrowserWindow getWindow(String windowId) {
        return windows.get(windowId);
    }

    public void createNewWindow(String windowId, Consumer<BrowserWindow.Builder> config) {
        BrowserWindow.Builder builder = new BrowserWindow.Builder(windowId);
        config.accept(builder);
        BrowserWindow window = builder.build();
        registerWindow(window);
    }
}
