// Backbone Server
// Nate Hunzaker
//
// Adds a module for server side interaction within Backbone using Connect


//-- Requirements ------------------------------------------------------//

var _          = require('underscore');
    Backbone   = require('backbone');
    express    = require('express'),
    ejs        = require('ejs');
    fs         = require('fs');

//-- Backbone Server ---------------------------------------------------//

Backbone.Server = function (options) {
    
    //-- Default Values ------------------------------------------------//
    var settings = {
        'port'         : 8000,
        'public'       : 'public',
        'views'        : 'views',
        'view engine'  : 'jade',
        'routes'       : {},
        'express'      : express.createServer(),
        'socketio'     : false
    };

    _.extend(this, settings, options);

    this._setup();
}

_.extend(Backbone.Server.prototype, Backbone.Events, {
    
    //-- Standard CRUD Routing Methods  --------------------------------//

    route: function (method, path, action) {
        this.routes[path] = [method, action]
    },

    get: function(path, action) {
        this.route('get', path, action);
    },

    post: function(path, action) {
        this.route('post', path, action);
    },

    put: function(path, action) {
        this.route('put', path, action);
    },

    delete: function(path, action) {
        this.route('delete', path, action);
    },

    _setup: function() {
        
        // Set static content folder
        this.express.use(express.static(this.public));
        
        // Set the view engine
        this.express.set('view engine', this['view engine']);    
        
        //-- SocketIO Methods  -----------------------------------------//
        
        if ( this['socketio'] ) {
            this.io = require('socket.io').listen(this.express);
            
            // A syntax sugar for socketIO
            this.bind = function(name, action) {
                this.io.sockets.on(name, action);
            }
            
            this.send = function(name, values) {
                this.io.sockets.emit(name, values);
            }

            this.events = function(events) {
                
                for (var e in events) {
                    this.bind(e, events[e]);
                }

            }
        }
    },

    //-- Server Methods ------------------------------------------------//

    start: function() {   

        // Add routes
        for (var i in this.routes) {
            
            var method = this.routes[i][0],
                action = this.routes[i][1];
            
            this.express[method](i, action);
        }
        
        // Add a route to load backbone:
        this.express.get('/backbone-server/backbone.js', function(req, res) {
                        
            var underscorejs = fs.readFileSync(__dirname + '/node_modules/underscore/underscore-min.js', 'utf-8'),
                backbonejs   = fs.readFileSync(__dirname + '/node_modules/backbone/backbone.js', 'utf-8');
            
            res.contentType('text/javascript');
            
            res.send(underscorejs + "\n" + backbonejs);
        
        });
        
        this.express.listen(this.port);
        console.log("Backbone Server is listening on port " + this.port);
    }
    
});


module.exports = Backbone;