package it.galgani.demos.bug;

import static com.codename1.ui.CN.*;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.javascript.JSObject;
import com.codename1.javascript.JavascriptContext;
import com.codename1.ui.BrowserComponent;
import com.codename1.ui.Command;
import com.codename1.ui.Toolbar;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.layouts.BorderLayout;
import java.io.IOException;

/**
 * This file was generated by <a href="https://www.codenameone.com/">Codename
 * One</a> for the purpose of building native mobile applications using Java.
 */
public class Bug {

    private Form current;
    private Resources theme;

    public void init(Object context) {
        theme = UIManager.initFirstTheme("/theme");

        // Enable Toolbar on all Forms by default
        Toolbar.setGlobalToolbar(true);

        // Pro only feature
        Log.bindCrashProtection(true);
    }

    public void start() {
        if (current != null) {
            current.show();
            return;
        }
        Form hi = new Form("MyBrowser", new BorderLayout());

        // Create the BrowserComponent
        BrowserComponent browser = new BrowserComponent();

        try {
            // Load a web page placed in the "html" package
            browser.setURLHierarchy("/index.html");
            Log.p("setURLHierarchy executed");
        } catch (IOException ex) {
            Log.e(ex);
        }

        hi.add(BorderLayout.CENTER, browser);

        // Javascript Bridge
        JavascriptContext context = new JavascriptContext(browser);
        JSObject document = (JSObject) context.get("document");

        Command backCommand = new Command("BackButton") {
            @Override
            public void actionPerformed(ActionEvent evt) {
                // browser.back();
                document.call("writeln", new Object[]{"Hello world"});
            }
        };

        hi.getToolbar().setBackCommand(backCommand);
        hi.show();
    }

    public void stop() {
        current = getCurrentForm();
        if (current instanceof Dialog) {
            ((Dialog) current).dispose();
            current = getCurrentForm();
        }
    }

    public void destroy() {
    }

}
