### 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/>
###

path = require('path')
{ Git } = require('treeeater')
#EventEmitter = require('events').EventEmitter
{ Stream } = require('stream')
git_commands = require('treeeater/build/default/git-commands').commands
{ request, debug_log } = require('./helper')
config = require('./config')

class NetGit extends Git
    constructor: (@opts) ->
        super @opts
        throw new Error("project cwd required") unless @opts?.cwd
        repopath = path.join(config.cwd, config.repositories)
        hashrepo = @opts.cwd[repopath.length+1 .. ]
        port = config.worker.git.port

        for func of @commands
            this[func] = do (func) ->
                (args..., callback) =>
                    debug_log(func)
                    ee = new Stream()
                    call = "/raw/#{hashrepo}/#{func}"
                    request port, 'POST', call, args, json: on, (err, buffer)->
                        data = buffer?.toString()
                        if data
                            try data = JSON.parse(data)
                            # if data isn't JSON encoded, it stays a String
                        # FIXME treeater has no errors?
                        # payload: not sure how to forward them
                        return callback(data) if callback
                        # TODO CLEAN UP
                        process.nextTick () ->
                            data.forEach (item) ->
                                ee.emit('data', item)
                            ee.emit('end')
                    return ee

# exports

module.exports = NetGit

