/**
 * server.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
**/

var dibs = require('../../core/dibs.js');
var DError = require('../../core/exception.js');
var async = require('async');
var _ = require('underscore');

module.exports.createServer = function (sid) {
    MessengerServer.prototype = dibs.BaseServer.createServer(sid, 'messenger');
    return new MessengerServer();
};

function MessengerServer() {
    var self = this;
    this.name = 'messenger';
    var configPath = dibs.config.getServerConfigRootDir(self);
    var extensions;

    this.getDefaultConfiguration = function (baseConfig) {
        return baseConfig;
    };

    this.OnServerStarting = function (callback) {
        self.status = 'RUNNING';

        extensions = dibs.plugin.getExtensions('dibs.server.messenger.method');

        async.series([
            function (cb) {
                _.each(extensions, function (m) {
                    return m.module.create(configPath);
                });
                cb(null);
            }
        ],
            function (err) {
                callback(err);
            });
    };

    this.OnServerStarted = function (callback) {
        callback(null);
    };

    this.OnServerTerminating = function (callback) {
        async.series([
            function (cb) {
                _.each(extensions, function (m) {
                    return m.module.close();
                });
                cb(null);
            }
        ],
            function (err) {
                callback(err);
            });
    };

    this.notifyInternal = function (method, subject, target, message, callback) {
        var methodObj = _.find(extensions, function (m) {
            return m.type === method;
        });
        methodObj.module.notify(subject, target, message, callback);
    };
}
