/**
 * exception.js
 * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Contact:
 * DongHee Yang <donghee.yang@samsung.com>
 * Sungmin Kim <sm.art.kim@samsung.com>
 * Jiil Hyoun <jiil.hyoun@samsung.com>
 * Jonghwan Park <iwin100.park@samsung.com>
 * Kitae Kim <kt920.kim@samsung.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 * - S-Core Co., Ltd
**/

require('js-yaml');
var $ = require('stringformat');
$.extendString('format');
var util = require('util');


var codes = {
    ERR001: 'Server Type \'{stype}\' is not in server Type list',
    ERR002: 'The server address(\'{host}:{port}\') is already in use!',
    ERR003: 'check your Error handler (one of try/catch not defined)',
    ERR004: 'Uncaught exception! => {stack}',
    ERR005: 'The server (\'{sid}\') is already in terminating!',
    ERR100: 'debug - {message}',

    NET001: 'Invalid connection from \'{host}\' is rejected!',

    RPC001: 'Connection \'{host}:{port}/{functionName}\' Failed!',
    RPC002: 'Connection \'{host}:{port}/{functionName}\' Timeout {sec} secounds!',
    RPC003: 'Remote function \'{host}:{port}/{functionName}\' is not defined!',
    RPC004: 'Local callback (\'{host}:{port}/{functionName}\') failed! - {stack}',
    RPC005: 'RPC (\'{host}:{port}/{functionName}\') Failed!',
    RPC006: '\'{stype}\' server can\'t route NOW!!',
    RPC007: 'callback function is not defined. (arguments: {arguments})',
    RPC008: 'RPC failed by disconnecting from remote server! \'{host}:{port}/{functionName}\' Maybe executing callback failed...',
    RPC009: 'RPC connection has been broken from \'{sid}/{functionName}\'',
    RPC010: 'Unauthorized RPC access is detected!',
    RPC011: 'Not found server type: {serverType}',

    SAH001: 'No action is scheduled... {key}',
    SAH002: 'Timeout scheduled action... {key}',
    LOG001: 'Can\'t connect to DB...',
    LOG002: 'Can\'t find to collection...'
};


var isInitialized = false;
function initialize() {
    var plugin = require('./plugin/plugin-manager');
    // Register server types
    var exts = plugin.getExtensions('dibs.base.errorCodes');
    if (exts && exts.length) {
        for (var i = 0; i < exts.length; i++) {
            var customCodes = exts[i].exception;
            for (var cCode in customCodes) {
                if (codes[cCode] !== undefined) {
                    var error = new Error('EXCEPTION001: Duplicate exception plugin code \'' +
                        cCode + '\' code must be uniq!');
                    console.log(error.message);
                } else {
                    codes[cCode] = customCodes[cCode];
                }
            }
        }
    }
    isInitialized = true;
}


var error = function (code, args, inner) {
    if (!isInitialized) {
        initialize();
    }

    var message = code + ': ' + codes[code];
    if (args) {
        message = message.format(args, inner);
    }
    if (inner) {
        message = message + ' - ' + util.inspect(inner);
    }
    Error.captureStackTrace(this, error); // use General stack trace collection API
    this.message = message;
    error.prototype.name = 'DibsError';
    this.errno = code;
    this.args = args;
    this.inner = inner;
};
util.inherits(error, Error);

module.exports = error;
