### codetube
    Copyright (C) 2011 payload payload@lavabit.com
    Copyright (C) 2011 dodo dodo.the.last@gmail.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero 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 Affero General Public License for more details.

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

util = require('util')
util.orginspect = util.inspect
util.inspect = require('eyes').inspector(stream: null, hexy:{format:'fours'})

require('colors')
express = require('express')
ascii = require('asciimo').Figlet
path = require('path')
io = require('socket.io')
io_session = require('socket.io-sessions')
Master = require('cluster/lib/master')
bridge = require('cluster-socket.io')
cluster = require('cluster')
config = require('./config')



class Cluster extends Master # test

    constructor: () ->
        super require('http').createServer()
        if @isMaster
            ascii.write config.name, 'Thin', (art) ->
                console.log(art.grey)
        if @isWorker
            @http = require('./http')
            @server = @http.server
        @gitdaemon = require('./git-daemon') if @isMaster
        @configure()

    configure: () =>
        console.log("configuring #{["worker","master"][0+@isMaster]} server …")

        sessionstore = config.session?()

        @http?.initialize(sessionstore)

        ws = io.listen(@server)
        if sessionstore
           ws = io_session.enable
               socket: ws
               parser: express.cookieParser()
               store: sessionstore

        @http?.websocket = @websocket = ws

        ws.enable('browser client minification') if config.socketio.minification
        ws.enable('browser client etag') if config.socketio.etag
        ws.set('store', new config.socketio.store) if config.socketio.store
        ws.set('resource', "/.sio")
        ws.set('log level', config.socketio.log_level)
        if config.socketio.transports
            ws.set('transports', config.socketio.transports)
        ws.set('close timeout', config.socketio.close_timeout)
        ws.set('heartbeat timeout', config.socketio.heartbeat.timeout)
        ws.set('heartbeat interval', config.socketio.heartbeat.interval)
        ws.set 'authorization', (handshake, authorize) ->
            authorize(null, yes)

        @set 'workers', config.cluster.workers
        @set 'socket path', '/tmp'
        @use cluster.logger(config.debug.logger) if config.debug.logger
        @use cluster.stats(connections:yes, requests:yes) if config.debug.stats
        @use cluster.repl(config.debug.repl) if config.debug.repl
        @use cluster.debug() if config.debug.enable

        Sio = require('./controller/sio')
        sio = new Sio()
        ws.of("/project").on 'connection', (socket) =>
            for own event, func of sio
                do ->
                    x = { func }
                    socket.on event, (data) =>
                        x.func(socket, data)

        @use bridge(ws)
        @listen config.port, config.host
        if @isMaster
            @gitdaemon.server.listen config.gitdaemon.port, config.gitdaemon.host
            console.log("http server listening on %s:%d …".magenta, @host, @port)

# exports

console.log("load config …")
config.check () ->
    module.exports.server = new Cluster

