/*=======================================================================
*
*   Copyright (C) 2014 Lysine.
*
*   Filename:    Global.js
*   Time:        2014/07/05
*   Author:      Lysine
*
*   Lysine is a student majoring in Software Engineering
*   from the School of Software, SUN YAT-SEN UNIVERSITY.
*
*   This program is free software: you can redistribute it and/or modify
*   it under the terms of the GNU General Public License as published by
*   the Free Software Foundation, either version 3 of the License, or
*   (at your option) any later version.
*
*   This program is distributed in the hope that it will be useful,
*   but WITHOUT ANY WARRANTY; without even the implied warranty of
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*   GNU General Public License for more details.

*   You should have received a copy of the GNU General Public License
*   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
=========================================================================*/

Global={};
Global.timers=[];

trace=function(text){
    callNative('Player.print',text);
};

clear=function(){
    callNative('Player.clear');
};

getTimer=function(){
    return callNative('Player.time');
};

timer=function(closure,delay){
    interval(closure,delay);
};

interval=function(closure,delay,times){
    if(times===undefined){
        times=1;
    }
	if(delay===undefined){
	    delay=1000;
	}
    var t={};
    t.trigger=callNative('Player.epoch')+delay;
	t.delay=delay;
	t.times=times;
    t.closure=closure;
    Global.timers.push(t);
};

Global._get=function(key){
    return callNative('System.get',key);
}
Global._=Global._get;
Global._set=function(key,val){
    callNative('System.set',key,val);
}

Global.step=function(time){
    Player.update();

    var cur=callNative('Player.epoch');
    for(var i=0;i<Global.timers.length;){
        var t=Global.timers[i];
        if(cur>=t.trigger){
		    try{
                t.closure();
			}
			catch(e){}
			switch(t.times){
			case 1:
                Global.timers.splice(i,1);
				break;
		    case 0:
			    t.trigger+=t.delay;
			    break;
			default:
			    t.times--;
			    t.trigger+=t.delay;
			    break;
		    }
        }
        else{
            i++;
        }
    }

    if(Player.state==='playing'){
        Display.root.step(time);
    }
    return Boolean(Global.timers.length||Display.root.children.length);
};

$G=Global;
