package core;

/*
 * Copyright (c) 2002-2007 TeamDev Ltd. All rights reserved.
 *
 * Use is subject to license terms.
 *
 * The complete licence text can be found at
 * http://www.teamdev.com/winpack/license.jsf
 */

import com.jniwrapper.win32.ie.Browser;
import com.jniwrapper.win32.ie.WebBrowser;
import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;
import java.awt.Component;

/**
 * Base class for JExplorer samples.
 *
 * @author Alexei Orischenko
 */
public abstract class BasicSample extends JFrame
{
    private WebBrowser _browser;
    private StringBuffer _log = new StringBuffer();

    protected BasicSample(String title)
    {
        super("JExplorer - " + title + " Sample");

        _browser = new Browser();

        setWindowProperties();
        createGui();
    }

    protected WebBrowser getBrowser()
    {
        return _browser;
    }

    protected void info(String msg)
    {
        _log.append(msg + "\r\n");
    }

    protected void clearLog()
    {
        _log = new StringBuffer();
    }

    protected void showLog()
    {
        showMessage(_log.toString());
    }

    protected void showLog(String title)
    {
        showMessage(title, _log.toString());
    }

    protected void showLogSwingLoop(String title)
    {
        showMessageSwingLoop(title, _log.toString());
    }

    protected void showMessage(String msg)
    {
        showMessage("JExplorer", msg);
    }

    protected void showMessage(final String title, final String msg)
    {
        JOptionPane.showMessageDialog((Component) _browser, msg, title, JOptionPane.INFORMATION_MESSAGE);
    }

    protected void showMessageSwingLoop(String msg)
    {
        showMessageSwingLoop("JExplorer", msg);
    }

    protected void showMessageSwingLoop(final String title, final String msg)
    {
        Runnable runnable = new Runnable()
        {
            public void run()
            {
                JOptionPane.showMessageDialog((Component) _browser, msg, title, JOptionPane.INFORMATION_MESSAGE);
            }
        };
        SwingUtilities.invokeLater(runnable);
    }

    protected void setWindowProperties()
    {
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    protected void createGui()
    {
        getContentPane().add((Component) _browser);
    }

    protected abstract void execute();

    public void run() throws Exception
    {
        BasicSample.setLookAndFeel();

        setVisible(true);

        execute();
    }

    private static void setLookAndFeel() throws Exception
    {
        UIManager.setLookAndFeel(WindowsLookAndFeel.class.getName());
    }
}
