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

var TB = TB || {};

// Client
TB.Client = {
    VERSION : 0.0,
    clientUrl : null,
    config : null,
    active : true,
    account : null,
    profile : null,
    session: null,
    init : function( serviceUrl, clientUrl ) {

        // Set clientUrl
        this.clientUrl = clientUrl ? clientUrl : 'https://www.tbuddy.de';

        // Init datetimepicker times
        moment.locale('de');
        Date.parseDate = function( input, format ){
            return moment(input,format).toDate();
        };
        Date.prototype.dateFormat = function( format ){
            return moment(this).format(format);
        };

        TB.Ext.Notification.init();     // Local notification - NOT push
        TB.Service.init( serviceUrl );
        TB.Client.initSessionDataFromCache();
        TB.Client.initConfig();
        TB.GUI.init();
        TB.Controller.init();

        TB.ICom.init();

        if ( this.featureDetection() ) {
            TB.Worker.init();
            TB.Worker.start();
        }

        TB.GUI.initFormValidator();

        // Init tracking
        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-83794586-1', 'auto');
        ga('send', 'pageview');
    },
    initConfig : function() {
        var ccfg = TB.Cache.get( 'config' ) ;

        ccfg = ( typeof ccfg == 'object' ) ? ccfg : {};

        ccfg.news_filter = ccfg.news_filter ? ccfg.news_filter : 'all';

        this.config = ccfg;
    },
    setConfig : function( key, value ) {
        this.config[ key ] = value;
        TB.Cache.set( 'config', this.config );
    },
    getConfig : function( key ) {
        return ( this.config[key] ? this.config[key] : null );
    },
    isLoggedIn: function() {
        return ( this.account != null && this.profile != null );
    },
    logout : function() {
        TB.Service.request( 'Auth', 'logout', { device_id : TB.Ext.Push.deviceId }, function() { } );
        TB.Client.account = null;
        TB.Client.profile = null;
        TB.Client.session = null;
        TB.Client.profiles = null;
        TB.Client.teams = null;

        TB.Client.destroySessionData();

        TB.GUI.removeTeamName();
    },
    setSessionData : function( account, profile, session, profiles, teams ) {
        TB.Client.account = account;
        TB.Client.profile = profile;
        TB.Client.session = session;
        TB.Client.profiles = profiles;
        TB.Client.teams = teams;

        // Store in cache
        TB.Cache.set( 'account', TB.Client.account );
        TB.Cache.set( 'profile', TB.Client.profile );
        TB.Cache.set( 'session', TB.Client.session );
        TB.Cache.set( 'profiles', TB.Client.profiles);
        TB.Cache.set( 'teams', TB.Client.teams );

        // Set session auth header
        TB.Service.setAuth(  { account_id : TB.Client.account.id, token: TB.Client.session.token } );
    },
    updateSessionProfile : function( profile ) {
        TB.Client.profile = profile;
        TB.Cache.set( 'profile', TB.Client.profile );
    },
    updateSessionProfiles : function( profiles ) {
        TB.Client.profiles = profiles;
        TB.Cache.set( 'profiles', TB.Client.profiles );
    },
    updateSessionAccount : function( newAccount ) {
        TB.Client.account = newAccount;
        TB.Cache.set( 'account', TB.Client.account);
    },
    updateSessionTeam : function( newTeam )
    {
        for ( var ti = 0; ti < TB.Client.teams.length; ti++ )
        {
            if ( TB.Client.teams[ ti ].id == newTeam.id )
            {
                TB.Client.teams[ ti ] = newTeam;
                break;
            }
        }
        TB.Cache.set( 'teams', TB.Client.teams );
    }
    ,
    initSessionDataFromCache : function() {
        TB.Client.account = TB.Cache.get( 'account' );
        TB.Client.profile = TB.Cache.get( 'profile' );
        TB.Client.session = TB.Cache.get( 'session' );
        TB.Client.profiles = TB.Cache.get( 'profiles' );
        TB.Client.teams = TB.Cache.get( 'teams' );

        // Set session auth header
        var accountId = ( TB.Client.account && TB.Client.account.id ) ? TB.Client.account.id : null,
            sessionToken = ( TB.Client.session && TB.Client.session.token ) ? TB.Client.session.token : null;
        TB.Service.setAuth(  { account_id : accountId, token: sessionToken } );
    },
    destroySessionData : function() {
        TB.Cache.clear();
    },
    getCurrentTeam : function() {
        var team = null;

        for ( var ti = 0; ti < this.teams.length; ti++ )
        {
            if ( this.teams[ ti ].id === this.profile.team_id )
            {
                team = this.teams[ ti ];
                break;
            }
        }

        return team;
    },
    getProfileRole : function() {
        var role = 'GUEST';
        if ( TB.Client.profile && TB.Client.profile.role )
        {
            role = TB.Client.profile.role.toUpperCase();
        }
        return role;
    },
    featureDetection : function() {
        if ( $('html').hasClass( 'no-cors' ) ) {
            TB.Ext.Notification.show(
                'Dein Browser wird nicht unterstützt. Wir empfehlen die Verwendung von Google Chrome.',
                TB.Ext.Notification.TYPE_DANGER
            );
            return false;
        } else {
            return true;
        }
    },
    can : function( right ) {

        var ret = false,
            role = ( TB.Client.profile ) ? "ROLE_" + TB.Client.profile.role.toUpperCase() : null;

        if ( null === role || false === TB.ACL.hasOwnProperty( role ) ) return ret;

        return ( -1 < TB.ACL[ role ].indexOf( right ) );

    }
};