// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var EventEmitter = require('./lib/event_emitter');
var inherits = require('util').inherits;
var util = require('util');
var errors = require('./errors');
var coerceRequestHandler = require('./request-handler');

function TChannelEndpointHandler(serviceName) {
    if (!(this instanceof TChannelEndpointHandler)) {
        return new TChannelEndpointHandler(serviceName);
    }
    var self = this;
    EventEmitter.call(self);
    self.handleEndpointEvent = self.defineEvent('handleEndpoint');

    self.serviceName = serviceName;
    self.endpoints = Object.create(null);
}
inherits(TChannelEndpointHandler, EventEmitter);

TChannelEndpointHandler.prototype.type = 'tchannel.endpoint-handler';

TChannelEndpointHandler.prototype.register = function register(name, options, handler) {
    var self = this;
    if (typeof options === 'function') {
        handler = options;
        options = {};
    }
    if (typeof handler !== 'function') {
        throw errors.InvalidHandlerError();
    }
    if (options.streamed) handler.canStream = true;
    self.endpoints[name] = coerceRequestHandler(handler, self, options);
    return handler;
};

TChannelEndpointHandler.prototype.handleRequest = function handleRequest(req, buildResponse) {
    var self = this;

    req.withArg1(function arg1Ready(err, arg1) {
        if (err) {
            // TODO: log error
            buildResponse({streamed: false}).sendError('UnexpectedError', util.format(
                'error accumulating arg1: %s: %s',
                err.constructor.name, err.message));
            return;
        }

        var name = String(arg1);
        var handler = self.endpoints[name];
        self.handleEndpointEvent.emit(self, {
            name: name,
            handler: handler
        });
        if (!handler) {
            buildResponse({streamed: false}).sendError('BadRequest', util.format(
                'no such endpoint service=%j endpoint=%j',
                req.serviceName, name));
        } else {
            handler.handleRequest(req, buildResponse);
        }
    });
};

TChannelEndpointHandler.prototype.withArg23 = function withArg23(req, buildResponse, handler) {
    req.withArg23(function gotArg23(err, arg2, arg3) {
        var res = buildResponse({streamed: false});
        if (err) {
            // TODO: log error
            res.sendError('UnexpectedError', util.format(
                'error accumulating arg2/arg3: %s: %s',
                err.constructor.name, err.message));
        } else {
            handler.handleRequest(req, res, arg2, arg3);
        }
    });
};

module.exports = TChannelEndpointHandler;

@@ -2395,406 +2395,52 @@
     
-req.withArg1(function arg1Ready(err, arg1) %7B%0A        if (err) %7B%0A            // TODO: log error%0A            buildResponse(%7Bstreamed: false%7D).sendError('UnexpectedError', util.format(%0A                'error accumulating arg1: %25s: %25s',%0A                err.constructor.name, err.message));%0A            return;%0A        %7D%0A%0A        var name = String(arg1);%0A        var handler = self.endpoints%5Bname%5D;%0A    
+var handler = self.endpoints%5Breq.endpoint%5D;%0A
     
@@ -2489,35 +2489,36 @@
     
-    
 name: 
-name,%0A   
+req.endpoint,%0A
         
  han
@@ -2509,25 +2509,24 @@
 nt,%0A        
- 
 handler: han
@@ -2530,20 +2530,16 @@
 handler%0A
-    
     %7D);%0A
@@ -2538,28 +2538,24 @@
     %7D);%0A    
-  
-  
 if (!handler
@@ -2554,28 +2554,24 @@
 !handler) %7B%0A
-    
         buil
@@ -2648,20 +2648,16 @@
         
- 
-   
 'no such
@@ -2703,20 +2703,16 @@
         
-    
 req.serv
@@ -2724,20 +2724,28 @@
 me, 
-name
+req.endpoint
 ));%0A    
     
@@ -2732,36 +2732,32 @@
 endpoint));%0A    
- 
-   
 %7D else %7B%0A       
@@ -2741,36 +2741,32 @@
 );%0A    %7D else %7B%0A
-    
         handler.
@@ -2800,37 +2800,25 @@
 ponse);%0A    
-    %7D%0A    %7D);
+%7D
 %0A%7D;%0A%0ATChanne

drop support for streaming arg1