package vassistent.ui;

import org.cef.CefApp;
import org.cef.CefClient;
import org.cef.CefSettings;
import org.cef.browser.CefBrowser;
import org.cef.handler.CefAppHandlerAdapter;

import javax.swing.*;
import java.awt.*;

/**
 * Embedded JCEF browser panel used to display the avatar pixel stream.
 */
public class PixelStreamingView extends JPanel {

    private static final long serialVersionUID = -5570653778104813836L;
    private final CefApp     cefApp;
    private final CefClient  client;
    private final CefBrowser browser;
    private final Component  browserUI_;

    /**
     * Creates an embedded Chromium browser panel.
     *
     * @param startURL initial URL to load
     * @param useOSR whether off-screen rendering is enabled
     * @param isTransparent whether transparent rendering is enabled
     */
    public PixelStreamingView(String startURL, boolean useOSR, boolean isTransparent) {
        super(new BorderLayout());
        setOpaque(true);
        setBackground(new Color(8, 11, 16));

        CefApp.addAppHandler(new CefAppHandlerAdapter(null) {
            /**
             * Handles JCEF application state transitions.
             *
             * @param state latest JCEF lifecycle state
             */
            @Override
            public void stateHasChanged(CefApp.CefAppState state) {
                if (state == CefApp.CefAppState.TERMINATED){
                    System.out.println("TERMINATED");
                }
            }
        });
        
        CefSettings settings = new CefSettings();
        settings.windowless_rendering_enabled = useOSR;
        
        cefApp = CefApp.getInstance(settings);
        client = cefApp.createClient();

        browser = client.createBrowser(startURL, useOSR, isTransparent);
        browserUI_ = browser.getUIComponent();

        JPanel browserContainer = new JPanel(new BorderLayout());
        browserContainer.setOpaque(true);
        browserContainer.setBackground(new Color(6, 9, 14));
        browserContainer.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(56, 68, 86)),
                BorderFactory.createEmptyBorder(6, 6, 6, 6)
        ));
        browserContainer.add(browserUI_, BorderLayout.CENTER);

        add(browserContainer, BorderLayout.CENTER);
    }
    
    /**
     * Disposes browser resources held by JCEF objects.
     */
    public void dispose() {
        if (browser != null) browser.close(true);
        if (client != null) client.dispose();
        if (cefApp != null) cefApp.dispose();
    }

    /**
     * Loads the given stream URL in the embedded browser.
     *
     * @param url stream URL
     */
    public void loadStream(String url) {
        browser.loadURL(url);
    }
}
