/**
 * Created by Benny on 12.10.2014.
 */
"use strict";

var TB = TB || {};

TB.Worker = {

    isStopped : false,

    init : function() {
        $( window).on( 'blur', function() {
            TB.Client.active = false;
        });
        $( window).on( 'focus', function() {
            TB.Client.active = true;
        });
    },

    start : function() {
        var time = 60000,       // 60 secs
            delta = 1000,
            tid;

        TB.Worker.isStopped = false;

        tid = setInterval(function() {
            time -= delta;
            if ( window.blurred ) { return; }
            if ( time <= 0 ) {
                clearInterval(tid);
                TB.Worker.execute();
            }
        }, delta);
    },

    stop : function()
    {
        TB.Worker.isStopped = true;
    },

    execute : function()
    {
        if ( TB.Worker.isStopped ) return;

        // Workers
        TB.Worker.cacheUpdate();

        // Start over
        TB.Worker.start();
    }

    ,


    cacheUpdate : function()
    {
        if ( !TB.Client.isLoggedIn() ) return;

        TB.Service.request( 'Profile', 'getCacheUpdate', {}, function(data)
        {
            if ( data && data.profile )
            {
                TB.Client.updateSessionProfile( data.profile );
            }
            if ( data && data.newsCount )
            {
                TB.GUI.updateNewsBadge( data.newsCount );
            }
            if ( data && data.team )
            {
                TB.Client.updateSessionTeam( data.team );
            }

        }, null, function() {} );
    }
};