// Copyright 2014, Renasar Technologies Inc.
/* jshint node: true */

'use strict';

var di = require('di'),
    fs = require('fs');

module.exports = nconfServiceFactory;

di.annotate(nconfServiceFactory, new di.Provide('Services.Configuration'));
di.annotate(nconfServiceFactory,
    new di.Inject(
        'nconf',
        'Protocol.Configuration',
        'Q'
    )
);

function nconfServiceFactory(nconf, configurationProtocol, Q) {
    function NconfService() {
        this.subscriptions = [];
        var defaults = process.cwd() + '/config.json',
            overrides = process.cwd() + '/overrides.json';

        nconf.use('memory');

        if (fs.existsSync(overrides)) {
            nconf.file('overrides', overrides);
        }

        nconf.argv()
            .env()
            .file('config', defaults);
    }

    NconfService.prototype.set = function set(key, value) {
        nconf.set(key, value);
    };

    NconfService.prototype.get = function get(key) {
        return nconf.get(key);
    };

    NconfService.prototype.start = function start() {
        var self = this;
        return Q.all([
            configurationProtocol.subscribeSet(self.set),
            configurationProtocol.subscribeGet(self.get)
        ])
        .spread(function(s1, s2) {
            self.subscriptions.push(s1);
            self.subscriptions.push(s2);
        });
    };

    NconfService.prototype.stop = function stop() {
        this.subscriptions.forEach(function (subscription) {
            subscription.dispose();
        });

        return Q.resolve();
    };

    return new NconfService();
}

@@ -144,21 +144,29 @@
 ports = 
-n
 conf
+iguration
 ServiceF
@@ -178,37 +178,45 @@
 y;%0A%0Adi.annotate(
-n
 conf
+iguration
 ServiceFactory, 
@@ -270,21 +270,29 @@
 nnotate(
-n
 conf
+iguration
 ServiceF
@@ -400,21 +400,29 @@
 unction 
-n
 conf
+iguration
 ServiceF
@@ -476,21 +476,29 @@
 unction 
-Nc
+C
 onf
+iguration
 Service(
@@ -864,29 +864,37 @@
 %0A    %7D%0A%0A    
-Nc
+C
 onf
+iguration
 Service.prot
@@ -967,37 +967,45 @@
 e);%0A    %7D;%0A%0A    
-Nc
+C
 onf
+iguration
 Service.prototyp
@@ -1067,37 +1067,45 @@
 y);%0A    %7D;%0A%0A    
-Nc
+C
 onf
+iguration
 Service.prototyp
@@ -1448,21 +1448,29 @@
 %7D;%0A%0A    
-Nc
+C
 onf
+iguration
 Service.
@@ -1669,13 +1669,21 @@
 new 
-Nc
+C
 onf
+iguration
 Serv

fix configuration service function names