/**
 * Created by aheadware
 */

"use strict";

var app = app || {};
app.core = app.core || {};

/**
 *
 * Dependencies:
 * RLite.min.js
 *
 * @type {{disable, enable, init, redirect, redirectExternal, reload}}
 *
 */
app.core.Controller = (function(){

    var rlite = null,
        prevHash = null,
        onTrigger = null,
        currentRoute = null,
        redirectRoute = null;

    var fnInitRoutes, fnTrigger;


    // start: private methods

    /**
     * Init routes
     */
    fnInitRoutes = function()
    {
        // start: auth
        rlite.add( 'auth/login', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AuthLogin(), r.params );
        });
        rlite.add( 'auth/login/:theme', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AuthLogin(), r.params );
        });
        rlite.add( 'auth/sso/:token/:theme', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AuthSso(), r.params );
        });
        rlite.add( 'auth/sso/:token', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AuthSso(), r.params );
        });
        rlite.add( 'auth/logout', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AuthLogout(), r.params );
        });
        rlite.add( 'auth/register', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AuthRegister(), r.params );
        });
        rlite.add( 'auth/register/:theme', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AuthRegister(), r.params );
        });
        rlite.add( 'auth/forgot-password', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AuthForgotPassword(), r.params );
        });
        rlite.add( 'auth/reset-password/:token', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AuthResetPassword(), r.params );
        });
        rlite.add( 'auth/validate-email/:token', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AuthValidateEmail(), r.params );
        });
        rlite.add( 'auth/join/:publicTeamId', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AuthJoin(), r.params );
        });
        rlite.add( 'auth/joinweb/:publicTeamId', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AuthJoinWeb(), r.params );
        });
        rlite.add( 'auth/start', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AuthStart(), r.params );
        });
        rlite.add( 'auth/startjoin/:publicTeamId', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AuthStartJoin(), r.params );
        });
        // stop: auth

        // start: course
        rlite.add( 'course/categories/:groupId', function( r )
        {
            app.core.StateManager.switchTo( new app.state.CourseCategories(), r.params );
        });
        rlite.add( 'course/templates/:groupId', function( r )
        {
            app.core.StateManager.switchTo( new app.state.CourseTemplates(), r.params );
        });
        // stop: course

        // start: dashboard
        rlite.add( 'home', function( r )
        {
            app.core.StateManager.switchTo( new app.state.Home(), r.params );
        });
        rlite.add( 'home/:flag', function( r )
        {
            app.core.StateManager.switchTo( new app.state.Home(), r.params );
        });
        // stop: dashboard

        // start: appointment
        rlite.add( 'appointment/create', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AppointmentCreate(), r.params );
        });
        rlite.add( 'appointment/edit/:id', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AppointmentEdit(), r.params );
        });
        rlite.add( 'appointment/edit/:id/serial', function( r )
        {
            r.params.serial = true;
            app.core.StateManager.switchTo( new app.state.AppointmentEdit(), r.params );
        });
        rlite.add( 'appointment/edit/:id/attendee', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AppointmentEditAttendee(), r.params );
        });
        rlite.add( 'appointment/edit/:id/attendee/serial', function( r )
        {
            r.params.serial = true;
            app.core.StateManager.switchTo( new app.state.AppointmentEditAttendee(), r.params );
        });
        rlite.add( 'appointment/:id', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AppointmentDetail(), r.params );
        });
        rlite.add( 'appointment/:id/attendee', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AppointmentDetailAttendee(), r.params );
        });
        rlite.add( 'appointment/:id/chat', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AppointmentDetailChat(), r.params );
        });
        rlite.add( 'appointment/notfound', function( r )
        {
            app.core.StateManager.switchTo( new app.state.AppointmentNotFound(), r.params );
        });
        // stop: appointment

        // start: configuration
        rlite.add( 'configuration/profile', function( r )
        {
            app.core.StateManager.switchTo( new app.state.ConfigurationProfile(), r.params );
        });
        rlite.add( 'configuration/attendance-log', function( r )
        {
            app.core.StateManager.switchTo( new app.state.ConfigurationAttendanceLog(), r.params );
        });
        rlite.add( 'configuration/privacy', function( r )
        {
            app.core.StateManager.switchTo( new app.state.ConfigurationPrivacy(), r.params );
        });
        rlite.add( 'configuration/privacy/edit', function( r )
        {
            app.core.StateManager.switchTo( new app.state.ConfigurationPrivacyEdit(), r.params );
        });
        rlite.add( 'configuration/profile/edit', function( r )
        {
            app.core.StateManager.switchTo( new app.state.ConfigurationProfileEdit(), r.params );
        });
        rlite.add( 'configuration/subprofile/edit', function( r )
        {
            app.core.StateManager.switchTo( new app.state.ConfigurationSubProfileEdit(), r.params );
        });
        rlite.add( 'configuration/profile/delete', function( r )
        {
            app.core.StateManager.switchTo( new app.state.ConfigurationProfileDelete(), r.params );
        });
        rlite.add( 'configuration/notifications', function( r )
        {
            app.core.StateManager.switchTo( new app.state.ConfigurationNotifications(), r.params );
        });
        rlite.add( 'configuration/account', function( r )
        {
            app.core.StateManager.switchTo( new app.state.ConfigurationAccount(), r.params );
        });
        rlite.add( 'configuration/contract', function( r )
        {
            app.core.StateManager.switchTo( new app.state.ConfigurationContract(), r.params );
        });
        rlite.add( 'configuration/contract/detail/:contractId', function( r )
        {
            app.core.StateManager.switchTo( new app.state.ConfigurationContractDetail(), r.params );
        });
        rlite.add( 'configuration/account/edit-password', function( r )
        {
            app.core.StateManager.switchTo( new app.state.ConfigurationAccountEditPassword(), r.params );
        });
        rlite.add( 'configuration/account/edit-address', function( r )
        {
            app.core.StateManager.switchTo( new app.state.ConfigurationAccountEditAddress(), r.params );
        });
        // stop: configuration


        // start: group(s)
        rlite.add( 'groups', function( r )
        {
            app.core.StateManager.switchTo( new app.state.Groups(), r.params );
        });
        rlite.add( 'group/:groupId', function( r )
        {
            app.core.StateManager.switchTo( new app.state.GroupDetail(), r.params );
        });
        rlite.add( 'group/:groupId/edit', function( r )
        {
            app.core.StateManager.switchTo( new app.state.GroupDetailEdit(), r.params );
        });
        rlite.add( 'group/:groupId/membermanagement', function( r )
        {
            app.core.StateManager.switchTo( new app.state.GroupMemberManagement(), r.params );
        });
        rlite.add( 'group/:groupId/membermanagement/:memberId', function( r )
        {
            app.core.StateManager.switchTo( new app.state.GroupMemberManagement(), r.params );
        });
        rlite.add( 'group/:groupId/members', function( r )
        {
            app.core.StateManager.switchTo( new app.state.GroupMembers(), r.params );
        });
        rlite.add( 'group/:groupId/invite', function( r )
        {
            app.core.StateManager.switchTo( new app.state.GroupInvite(), r.params );
        });
        rlite.add( 'group/:groupId/setting', function( r )
        {
            app.core.StateManager.switchTo( new app.state.GroupSetting(), r.params );
        });
        rlite.add( 'group/:groupId/leave', function( r )
        {
            app.core.StateManager.switchTo( new app.state.GroupLeave(), r.params );
        });
        // stop: group(s)

        // start: profile
        rlite.add( 'profile/:profileId', function( r )
        {
            app.core.StateManager.switchTo( new app.state.Profile(), r.params );
        });
        // stop: profile


        // start: message
        rlite.add( 'message/list', function( r )
        {
            app.core.StateManager.switchTo( new app.state.MessageList(), r.params );
        });
        rlite.add( 'message/:messageId', function( r )
        {
            app.core.StateManager.switchTo( new app.state.MessageDetail(), r.params );
        });
        rlite.add( 'message/create', function( r )
        {
            app.core.StateManager.switchTo( new app.state.MessageCreate(), r.params );
        });
        // stop: message


        // start: support
        rlite.add( 'about', function( r )
        {
            app.core.StateManager.switchTo( new app.state.About(), r.params );
        });
        // stop: support


        // start: stats
        rlite.add( 'stats/reporting', function( r )
        {
            app.core.StateManager.switchTo( new app.state.StatsReporting(), r.params );
        });
        rlite.add( 'stats/reporting/:groupId', function( r )
        {
            app.core.StateManager.switchTo( new app.state.StatsReporting(), r.params );
        });
        rlite.add( 'stats/planning', function( r )
        {
            app.core.StateManager.switchTo( new app.state.StatsPlanning(), r.params );
        });
        rlite.add( 'stats/planning/:groupId', function( r )
        {
            app.core.StateManager.switchTo( new app.state.StatsPlanning(), r.params );
        });
        rlite.add( 'stats/export', function( r )
        {
            app.core.StateManager.switchTo( new app.state.StatsExport(), r.params );
        });
        rlite.add( 'stats/export/:groupId', function( r )
        {
            app.core.StateManager.switchTo( new app.state.StatsExport(), r.params );
        });
        // stop: stats


        // start: support
        rlite.add( 'support', function( r )
        {
            app.core.StateManager.switchTo( new app.state.Support(), r.params );
        });
        // stop: support

        // start: error
        rlite.add( 'error/:errorCode', function( r )
        {
            app.core.StateManager.switchTo( new app.state.Error(), r.params );
        });
        // stop: error
    };

    /**
     * Trigger action
     */
    fnTrigger = function()
    {
        var hash = decodeURI( window.location.hash ) || '',
            hashArr, route, params = [];

        // Extract controller data from hash
        route = app.util.Helper.trim( hash, '#/' );
        hashArr = route.split( '/' );
        params = ( hashArr.length > 0 ) ? hashArr : null;

        // If no route is detected
        if ( "" === route )
        {
            // Resolve default route
            if ( app.core.Session.isLoggedIn() )
            {
                app.core.Controller.redirect( '#/home' );
            }
            else
            {
                // Check if this is the first time the app is launched
                if ( app.core.Session.hasLoggedInBefore() )
                {
                    app.core.Controller.redirect( '#/auth/login' );
                }
                else
                {
                    app.core.Controller.redirect( '#/auth/start' );
                }

            }
            return false;
        }

        // Process
        if ( rlite.exists( route ) )
        {
            rlite.run( route );
            currentRoute = route;
        }
        else
        {
            app.core.Controller.redirect( '#/error/404' );
        }
    };

    /**
     * Return publics
     */
    return {
        /**
         * Disable controller
         */
        disable : function()
        {
            $( window ).off( 'hashchange' );
        }
        ,
        /**
         * Enable controller
         */
        enable : function()
        {
            $( window ).on( 'hashchange', function( e )
            {
                // save old hash
                if ( e && e.originalEvent && e.originalEvent.oldURL )
                {
                    prevHash = e.originalEvent.oldURL.split( '#' );
                    if ( Array.isArray( prevHash ) && 2 == prevHash.length )
                    {
                        prevHash = prevHash[ 1 ];
                    }
                    else
                    {
                        prevHash = null;
                    }
                }

                fnTrigger();
            });
        }
        ,
        /**
         * Init
         */
        init : function()
        {
            rlite = new Rlite();
            fnInitRoutes();

            this.enable();

            fnTrigger();
        }
        ,
        getCurrentRoute : function()
        {
            return window.location.hash;
        }
        ,
        redirect : function( route )
        {
            window.location.hash = '/' + app.util.Helper.trim( route, '#/' );
        }
        ,
        getGetParam : function( name, url )
        {
            if (!url) url = window.location.hash;
            name = name.replace(/[\[\]]/g, '\\$&');
            var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, ' '));
        }
        ,
        redirectExternal : function()
        {
        }
        ,
        reload : function( hardReload )
        {
            app.core.StateManager.saveStateSettings();
            if ( hardReload )
            {
                window.location.reload(true);
            }
            else
            {
                fnTrigger();
            }
        }
    }

})();