package net.ranides.assira.ui.helpers;

import lombok.Data;
import lombok.experimental.UtilityClass;
import net.ranides.assira.events.Event;
import net.ranides.assira.events.EventLock;
import net.ranides.assira.events.EventReactor;
import net.ranides.assira.events.EventRouter;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

@UtilityClass
public class WindowUtils {

    public void close(Window frame) {
        frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
    }

    public boolean waitForFrame(JFrame frame) {
        EventLock<WindowClosing> lock = EventLock.lock(WindowClosing.class, Li.ROUTER);

        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                Li.ROUTER.signalEvent(new WindowClosing(frame));
            }
        });

        frame.setVisible(true);

        try {
            lock.waitForEvent(e -> e.source == frame);
            return true;
        } catch (InterruptedException e) {
            return false;
        }
    }

    @Data
    private static class WindowClosing implements Event {
        private final JFrame source;
    }

    static final class Li {
        static final EventRouter ROUTER = EventReactor.newInstance("assira.ui window observer");
    }

}
