(function() {
    var APP_NAME = "MANIFOLD"
    var APP_URL = "https://wizards.cyou/tablet/manifold.html";
    var APP_ICON = "https://wizards.cyou/tablet/manifold-icon.svg";

    var tablet = Tablet.getTablet("com.highfidelity.interface.tablet.system");
    var button = tablet.addButton({
        text: APP_NAME,
        icon: APP_ICON
    });

    var webEventHandler = function(data) {
        try {
            var msg = JSON.parse(data);
            if (msg.type === "ready") {
                var username = AccountServices.username || "";
                tablet.emitScriptEvent(JSON.stringify({
                    type: "username",
                    username: username
                }));
            }
        } catch(e) {
            print("Manifold web event error: " + e);
        }
    };

    button.clicked.connect(function() {
        tablet.gotoWebScreen(APP_URL);
        tablet.webEventReceived.connect(webEventHandler);
    });

    Script.scriptEnding.connect(function() {
        tablet.removeButton(button);
        tablet.webEventReceived.disconnect(webEventHandler);
    });
})();
