// EmLosso: Handle loss of WebGL context
// Copyright (c) 2014 Thomas Perl <m@thp.io>

// Use something like the following to patch out the hardcoded alert() from the app JS:
// sed -i -e "s,alert('WebGL context lost. You will need to reload the page.');,," app.js

EmLosso = {
    contextLost: false,

    isContextLost: function () {
        if (EmLosso.contextLost) {
            EmLosso.contextLost = false;
            return 1;
        }

        return 0;
    },

    simulateLoss: function() {
        //var gl = Module.canvas.getContext('webgl') || Module.canvas.getContext("experimental-webgl");
        var gl = Module.canvas.getContext("experimental-webgl");
        var ext = gl.getExtension('WEBGL_lose_context');
        ext.loseContext(); // trigger a context loss
        //ext.restoreContext(); // restores the context
    },

    install: function () {
        var c = Module.canvas;
        c.addEventListener('webglcontextlost', function(event) {
            // Important, so we get an event when it's restored
            event.preventDefault();
        }, false);

        c.addEventListener('webglcontextrestored', function (event) {
            // At this point, set the flag, so C++ code can restore the context
            EmLosso.contextLost = true;
        }, false);
    }
};

EmLosso.install();
