<commit_before>/**
 * Created with JetBrains RubyMine.
 * User: teamco
 * Date: 11/4/12
 * Time: 10:14 PM
 * To change this template use File | Settings | File Templates.
 */

define([
    'modules/observer',
    'modules/logger'
], function defineMVC(Observer, Logger) {

    /**
     * Define MVC
     * @class MVC
     * @param opts
     * @constructor
     */
    var MVC = function MVC(opts) {

        /**
         * Define scope
         * @type {mvc.scope}
         */
        this.scope = opts.scope;

        /**
         * Define MVC Relationship from -> to
         * @type {Array}
         */
        this.RELATIONS = [
            ['Controller', 'Model'],
            ['View', 'Controller']
        ];

        /**
         * Define local defaults
         * @type {string[]}
         */
        var singular = [
                'Workspace',
                'Page',
                'Widget'
            ],
            plural = [
                'Workspaces',
                'Pages',
                'Widgets'
            ];

        /**
         * Define reserved methods
         * @type {{
         *  create: {singular: Array},
         *  destroy: {singular: Array, plural: Array}
         * }}
         */
        this.RESERVED = {
            resize: {
                singular: singular,
                plural: plural
            },
            create: {
                singular: singular
            },
            destroy: {
                singular: singular,
                plural: plural
            }
        };

        /**
         * Define default listeners
         * @type {*}
         */
        this.defaultListeners = {
            'before.init.config': 'getConfigLog',
            'after.init.config': 'getConfigLog',
            'success.created': 'successCreated',
            'success.rendered': 'successRendered',
            'after.create.item': 'afterCreateItem',
            'after.destroy.item': 'afterDestroyItem',
            'after.destroy.items': 'afterDestroyItems',
            'after.resize.window': 'afterResizeWindow'
        };

        /**
         * Reset opts
         * @type {*}
         */
        opts = anthill.base.define(opts, {}, true);

        /**
         * Apply Configure
         * Define selfConfig
         * @type {*}
         */
        var selfConfig = anthill.base.define(opts.config[0], {}, true);

        /**
         * Define selfDefaults
         * @type {*}
         */
        var selfDefaults = anthill.base.define(opts.config[1], {}, true);

        /**
         * Define scope config
         * @type {mvc.scope.config}
         */
        this.scope.config = anthill.base.lib.hash.extendHash(
            selfConfig,
            selfDefaults
        );

        /**
         * Define mvc components
         * @type {mvc.components}
         */
        this.components = anthill.base.define(
            opts.components,
            [opts.components],
            true
        );

        /**
         * Define mvc config
         * @type {mvc.config}
         */
        this.config = anthill.base.define(selfConfig, {}, true);

        /**
         * Define mvc force creating components
         * @type {Boolean}
         */
        this.force = anthill.base.defineBoolean(opts.force, false, true);

        /**
         * Define mvc render
         * @type {Boolean}
         */
        this.render = anthill.base.defineBoolean(opts.render, true, true);

        var config = {},
            scope = this.scope;

        scope.eventmanager = {};

        $.extend(config, scope.config);

        /**
         * Define containment
         * @type {mvc.defineContainment}
         */
        this.defineContainment();

        /**
         * Define mvc applyLogger
         * @type {mvc.applyLogger}
         */
        this.applyLogger();

        /**
         * Define mvc applyConfig
         * @type {mvc.applyConfig}
         */
        this.applyConfig();

        /**
         * Define mvc applyMVC
         * @type {mvc.applyMVC}
         */
        this.applyMVC();

        /**
         * Define mvc applyObserver
         * @type {mvc.applyObserver}
         */
        this.applyObserver();

        /**
         * Define mvc applyEventManager
         * @type {mvc.applyEventManager}
         */
        this.applyEventManager();

        /**
         * Define mvc applyPermissions
         * @type {mvc.applyPermissions}
         */
        this.applyPermissions();

        /**
         * Define local instance of eventList
         * @type {*}
         */
        var eventList = scope.eventmanager.eventList;

        if (eventList) {

            /**
             * Publish before InitConfig event
             */
            scope.observer.publish(
                eventList.beforeInitConfig, [
                    'Config before create',
                    config
                ]
            );

            /**
             * Publish after InitConfig event
             */
            scope.observer.publish(
                eventList.afterInitConfig, [
                    'Config after create',
                    scope.config
                ]
            );
        }
    };

    return MVC.extend({

        /**
         * Define parent node
         */
        defineContainment: function defineContainment() {

            var scope = this.scope,
                config = scope.config;

            if (anthill.base.isDefined(config.containment)) {

                /**
                 * Define parent node
                 * @type {*}
                 */
                scope.containment = config.containment;
                delete config.containment;
            }
        },

        /**
         * Define MVC
         * @param {Function|String} mvcPattern
         * @param {Boolean} [force]
         */
        defineMVC: function defineMVC(mvcPattern, force) {

            var base = anthill.base,
                name = base.isString(mvcPattern) ?
                    mvcPattern :
                    mvcPattern.name.toLowerCase(),
                scope = this.scope;

            if (base.isFunction(mvcPattern)) {

                scope[name] = new mvcPattern();

            } else {

                if (force) {

                    var scopeName = scope.constructor.name.toLowerCase();

                    var fn = new Function(
                        scopeName,
                        [
                            'return function ', mvc,
                            '(', scopeName, ') { this.scope = ', scopeName, '; };'
                        ].join('')
                    );

                    scope[name.toLowerCase()] = new (new fn(scope))(scope);

                    mvcPattern = scope[name.toLowerCase()].constructor;

                }
            }

            return mvcPattern;

        },

        /**
         * Set relation between MVC components
         */
        setRelation: function setRelation() {
            var relations = this.RELATIONS,
                i = 0, l = relations.length,
                from, to,
                scope = this.scope,
                base = anthill.base;

            for (i; i < l; i += 1) {
                var relation = relations[i];
                from = relation[0].toLowerCase();
                to = relation[1].toLowerCase();
                if (base.isDefined(scope[from]) &&
                    base.isDefined(scope[to])) {
                    scope[from][to] = scope[to];
                }
            }

        },

        /**
         * Apply MVC
         * @returns {boolean}
         */
        applyMVC: function applyMVC() {
            var i = 0,
                l = this.components.length;

            for (i; i < l; i += 1) {
                var mvc = this.components[i];

                if (!anthill.base.isDefined(mvc)) {
                    return false;
                }

                var pattern = this.defineMVC(mvc, this.force).name.toLowerCase(),
                    ref = this.scope[pattern];

                ref.scope = this.scope;

                if (pattern === 'view') {

                    /**
                     * Define elements
                     * @type {{}}
                     */
                    this.scope.view.elements = {};
                }
            }

            this.setRelation();
        },

        /**
         * Apply config
         */
        applyConfig: function applyConfig() {
            var base = anthill.base,
                scope = this.scope,
                timestamp = base.lib.datetime.timestamp(
                    this.config.timestamp
                ),
                config = scope.config;

            config.uuid = base.lib.generator.UUID(this.config.uuid);
            config.timestamp = timestamp;

            if (this.render) {
                config.html = base.define(config.html, {}, true);
                config.html.selector = '.' + scope.constructor.name.toLowerCase();
            }
        },

        /**
         * Apply event manager
         */
        applyEventManager: function applyEventManager() {

            var scope = this.scope,
                base = anthill.base,
                eventManager = scope.eventmanager;

            if (base.isDefined(eventManager)) {

                eventManager.scope = scope;
                eventManager.abstract = base.define(
                    eventManager.abstract, {}, true
                );

                var eventList = eventManager.eventList,
                    index;

                for (index in eventList) {

                    if (eventList.hasOwnProperty(index)) {

                        var event = eventList[index],
                            callback = scope.controller[index];

                        if (!base.isDefined(callback)) {
                            var method = index.toPoint().split('.'),
                                key = method[0];

                            method.shift();
                            method = ('.' + method.join('.')).toCamel();

                            if (this.RESERVED.hasOwnProperty(key)) {

                                if ($.inArray(method, this.RESERVED[key].singular) > -1) {

                                    eventManager.abstract[key + 'Item'] = index;
                                    callback = scope.controller[key + 'Item'];
                                } else if ($.inArray(method, this.RESERVED[key].plural) > -1) {

                                    eventManager.abstract[key + 'Items'] = index;
                                    callback = scope.controller[key + 'Items'];
                                } else {

                                    this.scope.logger.warn(
                                        'Undefined Event Callback', [
                                            scope.controller,
                                                key + method
                                        ]
                                    );
                                }
                            }
                        }

                        eventManager.subscribe({
                            event: event,
                            callback: callback
                        }, true);
                    }
                }

                this.applyDefaultListeners();

                scope.logger.debug('Subscribe events', eventManager);

                this.applyListeners('local');
                this.applyListeners('global');

            } else {

                scope.logger.warn('Undefined Event manager', scope.eventmanager);
            }
        },

        /**
         * Apply default listeners
         */
        applyDefaultListeners: function applyDefaultListeners() {

            /**
             * Local instance of default listeners
             * @type {*}
             */
            var listeners = this.defaultListeners;

            for (var index in listeners) {

                if (listeners.hasOwnProperty(index)) {

                    this.scope.eventmanager.subscribe({
                        event: index,
                        callback: this.scope.controller[listeners[index]]
                    }, true);
                }
            }
        },

        /**
         * Apply listeners
         */
        applyListeners: function applyListeners(type) {

            var index, event,
                scope = this.scope,
                listener = type + 'Listeners';

            if (typeof scope[listener] === 'object') {

                for (index in scope[listener]) {

                    if (scope[listener].hasOwnProperty(index)) {

                        /**
                         * Define local instance of an event
                         * @type {*}
                         */
                        event = scope[listener][index];

                        if (!anthill.base.isArray(event)) {
                            event = [event];
                        }

                        for (var i = 0, l = event.length; i < l; i++) {

                            scope.eventmanager.subscribe({
                                event: {
                                    eventName: event[i].name,
                                    params: event[i].params,
                                    scope: event[i].scope
                                },
                                callback: event[i].callback
                            }, false);
                        }
                    }
                }
            }

            scope.logger.debug('Apply ' + type + ' listeners', scope[listener]);
        },

        /**
         * Define permissions
         * @returns {boolean}
         */
        applyPermissions: function applyPermissions() {

            if (!this.scope.config.hasOwnProperty('plugin')) {
                this._applyPermissions('local');
                this._applyPermissions('global');
            }

            var scope = this.scope,
                permission = scope.permission;

            if (scope.controller.checkCondition({
                condition: !anthill.base.isDefined(permission),
                type: 'warn',
                msg: 'Undefined permission'
            })) {
                return false;
            }

            permission.capability = {};

            anthill.base.isFunction(permission.config) ?
                permission.config() :
                scope.logger.warn('Force created permissions', permission);

            scope.logger.debug('Local permissions', permission);

        },

        /**
         * Apply global permissions
         * @returns {*|boolean}
         */
        _applyPermissions: function _applyPermissions(type) {
            var base = anthill.base,
                scope = this.scope,
                mode = scope.controller.getMode(),
                permission = type + 'Permissions';

            if (scope.controller.checkCondition({
                condition: !base.isDefined(mode),
                type: 'warn',
                msg: 'Undefined ' + type + ' mode'
            })) {
                return false;
            }

            if (scope.controller.checkCondition({
                condition: !base.isDefined(scope[permission]),
                type: 'warn',
                msg: 'Undefined ' + type + ' permission'
            })) {
                return false;
            }

            var capabilities = scope[permission][mode];

            if (scope.controller.checkCondition({
                condition: !base.isDefined(capabilities),
                type: 'warn',
                msg: 'Undefined ' + type + ' capabilities',
                args: mode
            })) {
                return false;
            }

            scope.logger.debug('Apply ' + type + ' permissions', capabilities);

            if (!base.isDefined(scope.config.permission)) {
                scope.config.permission = {};
            }

            $.extend(scope.config.permission, capabilities);
        },

        /**
         * Apply Observer
         */
        applyObserver: function applyObserver() {
            var scope = this.scope;
            scope.observer = new Observer();
            scope.observer.scope = scope;
        },

        /**
         * Apply Logger
         */
        applyLogger: function applyLogger() {
            var scope = this.scope,
                base = anthill.base,
                config = scope.config.logger;

            scope.logger = new Logger(scope);

            if (base.isDefined(config)) {
                Logger.prototype.config = config || {};
            }

            scope.logger.defineLogs();
        }

    });

});<commit_msg>add comments<commit_after>/**
 * Created with JetBrains RubyMine.
 * User: teamco
 * Date: 11/4/12
 * Time: 10:14 PM
 * To change this template use File | Settings | File Templates.
 */

define([
    'modules/observer',
    'modules/logger'
], function defineMVC(Observer, Logger) {

    /**
     * Define MVC
     * @class MVC
     * @param opts
     * @constructor
     */
    var MVC = function MVC(opts) {

        /**
         * Define scope
         * @type {mvc.scope}
         */
        this.scope = opts.scope;

        /**
         * Define MVC Relationship from -> to
         * @type {Array}
         */
        this.RELATIONS = [
            ['Controller', 'Model'],
            ['View', 'Controller']
        ];

        /**
         * Define local defaults
         * @type {string[]}
         */
        var singular = [
                'Workspace',
                'Page',
                'Widget'
            ],
            plural = [
                'Workspaces',
                'Pages',
                'Widgets'
            ];

        /**
         * Define reserved methods
         * @type {{
         *  create: {singular: Array},
         *  destroy: {singular: Array, plural: Array}
         * }}
         */
        this.RESERVED = {
            resize: {
                singular: singular,
                plural: plural
            },
            create: {
                singular: singular
            },
            destroy: {
                singular: singular,
                plural: plural
            }
        };

        /**
         * Define default listeners
         * @type {*}
         */
        this.defaultListeners = {
            'before.init.config': 'getConfigLog',
            'after.init.config': 'getConfigLog',
            'success.created': 'successCreated',
            'success.rendered': 'successRendered',
            'after.create.item': 'afterCreateItem',
            'after.destroy.item': 'afterDestroyItem',
            'after.destroy.items': 'afterDestroyItems',
            'after.resize.window': 'afterResizeWindow'
        };

        /**
         * Reset opts
         * @type {*}
         */
        opts = anthill.base.define(opts, {}, true);

        /**
         * Apply Configure
         * Define selfConfig
         * @type {*}
         */
        var selfConfig = anthill.base.define(opts.config[0], {}, true);

        /**
         * Define selfDefaults
         * @type {*}
         */
        var selfDefaults = anthill.base.define(opts.config[1], {}, true);

        /**
         * Define scope config
         * @type {mvc.scope.config}
         */
        this.scope.config = anthill.base.lib.hash.extendHash(
            selfConfig,
            selfDefaults
        );

        /**
         * Define mvc components
         * @type {mvc.components}
         */
        this.components = anthill.base.define(
            opts.components,
            [opts.components],
            true
        );

        /**
         * Define mvc config
         * @type {mvc.config}
         */
        this.config = anthill.base.define(selfConfig, {}, true);

        /**
         * Define mvc force creating components
         * @type {Boolean}
         */
        this.force = anthill.base.defineBoolean(opts.force, false, true);

        /**
         * Define mvc render
         * @type {Boolean}
         */
        this.render = anthill.base.defineBoolean(opts.render, true, true);

        var config = {},
            scope = this.scope;

        scope.eventmanager = {};

        $.extend(config, scope.config);

        /**
         * Define containment
         * @type {mvc.defineContainment}
         */
        this.defineContainment();

        /**
         * Define mvc applyLogger
         * @type {mvc.applyLogger}
         */
        this.applyLogger();

        /**
         * Define mvc applyConfig
         * @type {mvc.applyConfig}
         */
        this.applyConfig();

        /**
         * Define mvc applyMVC
         * @type {mvc.applyMVC}
         */
        this.applyMVC();

        /**
         * Define mvc applyObserver
         * @type {mvc.applyObserver}
         */
        this.applyObserver();

        /**
         * Define mvc applyEventManager
         * @type {mvc.applyEventManager}
         */
        this.applyEventManager();

        /**
         * Define mvc applyPermissions
         * @type {mvc.applyPermissions}
         */
        this.applyPermissions();

        /**
         * Define local instance of eventList
         * @type {*}
         */
        var eventList = scope.eventmanager.eventList;

        if (eventList) {

            /**
             * Publish before InitConfig event
             */
            scope.observer.publish(
                eventList.beforeInitConfig, [
                    'Config before create',
                    config
                ]
            );

            /**
             * Publish after InitConfig event
             */
            scope.observer.publish(
                eventList.afterInitConfig, [
                    'Config after create',
                    scope.config
                ]
            );
        }
    };

    return MVC.extend({

        /**
         * Define parent node
         */
        defineContainment: function defineContainment() {

            var scope = this.scope,
                config = scope.config;

            if (anthill.base.isDefined(config.containment)) {

                /**
                 * Define parent node
                 * @type {*}
                 */
                scope.containment = config.containment;
                delete config.containment;
            }
        },

        /**
         * Define MVC
         * @param {Function|String} mvcPattern
         * @param {Boolean} [force]
         */
        defineMVC: function defineMVC(mvcPattern, force) {

            var base = anthill.base,
                name = base.isString(mvcPattern) ?
                    mvcPattern :
                    mvcPattern.name.toLowerCase(),
                scope = this.scope;

            if (base.isFunction(mvcPattern)) {

                /**
                 * Define pattern
                 * @type {mvcPattern}
                 */
                scope[name] = new mvcPattern();

            } else {

                if (force) {

                    /**
                     * Define scope name
                     * @type {string}
                     */
                    var scopeName = scope.constructor.name.toLowerCase();

                    /**
                     * Define function
                     * @type {Function}
                     */
                    var fn = new Function(
                        scopeName,
                        [
                            'return function ', mvcPattern,
                            '(', scopeName, ') { this.scope = ', scopeName, '; };'
                        ].join('')
                    );

                    scope[name.toLowerCase()] = new (new fn(scope))(scope);

                    /**
                     * Set pattern
                     * @type {constructor|r.constructor|constructor.constructor|number|Function}
                     */
                    mvcPattern = scope[name.toLowerCase()].constructor;
                }
            }

            return mvcPattern;

        },

        /**
         * Set relation between MVC components
         */
        setRelation: function setRelation() {
            var relations = this.RELATIONS,
                i = 0, l = relations.length,
                from, to,
                scope = this.scope,
                base = anthill.base;

            for (i; i < l; i += 1) {
                var relation = relations[i];
                from = relation[0].toLowerCase();
                to = relation[1].toLowerCase();
                if (base.isDefined(scope[from]) &&
                    base.isDefined(scope[to])) {
                    scope[from][to] = scope[to];
                }
            }

        },

        /**
         * Apply MVC
         * @returns {boolean}
         */
        applyMVC: function applyMVC() {
            var i = 0,
                l = this.components.length;

            for (i; i < l; i += 1) {
                var mvc = this.components[i];

                if (!anthill.base.isDefined(mvc)) {
                    return false;
                }

                var pattern = this.defineMVC(mvc, this.force).name.toLowerCase(),
                    ref = this.scope[pattern];

                ref.scope = this.scope;

                if (pattern === 'view') {

                    /**
                     * Define elements
                     * @type {{}}
                     */
                    this.scope.view.elements = {};
                }
            }

            this.setRelation();
        },

        /**
         * Apply config
         */
        applyConfig: function applyConfig() {
            var base = anthill.base,
                scope = this.scope,
                timestamp = base.lib.datetime.timestamp(
                    this.config.timestamp
                ),
                config = scope.config;

            config.uuid = base.lib.generator.UUID(this.config.uuid);
            config.timestamp = timestamp;

            if (this.render) {
                config.html = base.define(config.html, {}, true);
                config.html.selector = '.' + scope.constructor.name.toLowerCase();
            }
        },

        /**
         * Apply event manager
         */
        applyEventManager: function applyEventManager() {

            var scope = this.scope,
                base = anthill.base,
                eventManager = scope.eventmanager;

            if (base.isDefined(eventManager)) {

                eventManager.scope = scope;
                eventManager.abstract = base.define(
                    eventManager.abstract, {}, true
                );

                var eventList = eventManager.eventList,
                    index;

                for (index in eventList) {

                    if (eventList.hasOwnProperty(index)) {

                        var event = eventList[index],
                            callback = scope.controller[index];

                        if (!base.isDefined(callback)) {
                            var method = index.toPoint().split('.'),
                                key = method[0];

                            method.shift();
                            method = ('.' + method.join('.')).toCamel();

                            if (this.RESERVED.hasOwnProperty(key)) {

                                if ($.inArray(method, this.RESERVED[key].singular) > -1) {

                                    eventManager.abstract[key + 'Item'] = index;
                                    callback = scope.controller[key + 'Item'];
                                } else if ($.inArray(method, this.RESERVED[key].plural) > -1) {

                                    eventManager.abstract[key + 'Items'] = index;
                                    callback = scope.controller[key + 'Items'];
                                } else {

                                    this.scope.logger.warn(
                                        'Undefined Event Callback', [
                                            scope.controller,
                                                key + method
                                        ]
                                    );
                                }
                            }
                        }

                        eventManager.subscribe({
                            event: event,
                            callback: callback
                        }, true);
                    }
                }

                this.applyDefaultListeners();

                scope.logger.debug('Subscribe events', eventManager);

                this.applyListeners('local');
                this.applyListeners('global');

            } else {

                scope.logger.warn('Undefined Event manager', scope.eventmanager);
            }
        },

        /**
         * Apply default listeners
         */
        applyDefaultListeners: function applyDefaultListeners() {

            /**
             * Local instance of default listeners
             * @type {*}
             */
            var listeners = this.defaultListeners;

            for (var index in listeners) {

                if (listeners.hasOwnProperty(index)) {

                    this.scope.eventmanager.subscribe({
                        event: index,
                        callback: this.scope.controller[listeners[index]]
                    }, true);
                }
            }
        },

        /**
         * Apply listeners
         */
        applyListeners: function applyListeners(type) {

            var index, event,
                scope = this.scope,
                listener = type + 'Listeners';

            if (typeof scope[listener] === 'object') {

                for (index in scope[listener]) {

                    if (scope[listener].hasOwnProperty(index)) {

                        /**
                         * Define local instance of an event
                         * @type {*}
                         */
                        event = scope[listener][index];

                        if (!anthill.base.isArray(event)) {
                            event = [event];
                        }

                        for (var i = 0, l = event.length; i < l; i++) {

                            scope.eventmanager.subscribe({
                                event: {
                                    eventName: event[i].name,
                                    params: event[i].params,
                                    scope: event[i].scope
                                },
                                callback: event[i].callback
                            }, false);
                        }
                    }
                }
            }

            scope.logger.debug('Apply ' + type + ' listeners', scope[listener]);
        },

        /**
         * Define permissions
         * @returns {boolean}
         */
        applyPermissions: function applyPermissions() {

            if (!this.scope.config.hasOwnProperty('plugin')) {
                this._applyPermissions('local');
                this._applyPermissions('global');
            }

            var scope = this.scope,
                permission = scope.permission;

            if (scope.controller.checkCondition({
                condition: !anthill.base.isDefined(permission),
                type: 'warn',
                msg: 'Undefined permission'
            })) {
                return false;
            }

            permission.capability = {};

            anthill.base.isFunction(permission.config) ?
                permission.config() :
                scope.logger.warn('Force created permissions', permission);

            scope.logger.debug('Local permissions', permission);

        },

        /**
         * Apply global permissions
         * @returns {*|boolean}
         */
        _applyPermissions: function _applyPermissions(type) {
            var base = anthill.base,
                scope = this.scope,
                mode = scope.controller.getMode(),
                permission = type + 'Permissions';

            if (scope.controller.checkCondition({
                condition: !base.isDefined(mode),
                type: 'warn',
                msg: 'Undefined ' + type + ' mode'
            })) {
                return false;
            }

            if (scope.controller.checkCondition({
                condition: !base.isDefined(scope[permission]),
                type: 'warn',
                msg: 'Undefined ' + type + ' permission'
            })) {
                return false;
            }

            var capabilities = scope[permission][mode];

            if (scope.controller.checkCondition({
                condition: !base.isDefined(capabilities),
                type: 'warn',
                msg: 'Undefined ' + type + ' capabilities',
                args: mode
            })) {
                return false;
            }

            scope.logger.debug('Apply ' + type + ' permissions', capabilities);

            if (!base.isDefined(scope.config.permission)) {
                scope.config.permission = {};
            }

            $.extend(scope.config.permission, capabilities);
        },

        /**
         * Apply Observer
         */
        applyObserver: function applyObserver() {
            var scope = this.scope;
            scope.observer = new Observer();
            scope.observer.scope = scope;
        },

        /**
         * Apply Logger
         */
        applyLogger: function applyLogger() {
            var scope = this.scope,
                base = anthill.base,
                config = scope.config.logger;

            scope.logger = new Logger(scope);

            if (base.isDefined(config)) {
                Logger.prototype.config = config || {};
            }

            scope.logger.defineLogs();
        }

    });

});<|endoftext|>


<commit_before>angular.module('modelCompanyApp').
directive('timeseries', ['$window', 'ObjectService',
    function($window, ObjectService) {
        return {
            restrict: 'A',
            scope: {
                data: "=",
                events: "=",
                attribute: "@",
                filter: "=",
                mess: "@"
            },
            link: function(scope, element, attrs) {

                var context, x;
                var circleSize = 12;

                scope.$watch('data', function(newVal) {
                    if (newVal)
                        render(newVal);
                });

                scope.$watch('filter', function(newVal) {
                    if (context && newVal)
                        update(newVal)
                }, true)

                function update(filter) {

                    var data = ObjectService.constructWithFilter(scope.data, scope.attribute, filter);

                    // DATA JOIN
                    var circ = context.selectAll(".circ")
                        .data(data);

                    // UPDATE
                    circ.transition().duration(500)
                        .attr("r", function(d) {
                            return Math.min(50, Math.max(10, 20 * Math.log(d.value)));
                        })

                    circ.attr("cx", function(d) {
                            return x(getDate(d.label));
                        })
                        .attr("cy", function(d, i) {
                            return circleSize * 2;
                        }).on('click', function(d) {
                            console.log(d)
                        })

                    circ.selectAll('title')
                        .text(function(d) {
                            return d.value;
                        })

                    // ENTER
                    var enterCirc = circ.enter().append("circle")
                        .attr("class", "circ")
                        .attr("cx", function(d) {
                            return x(getDate(d.label));
                        })
                        .attr("r", 0)
                        .attr("cy", function(d, i) {
                            return circleSize * 2;
                        })

                    enterCirc.transition().duration(500)
                        .attr("r", function(d) {
                            console.log(d)
                            return Math.min(50, Math.max(10, 20 * Math.log(d.value)));
                        })

                    circ.append("svg:title").text(function(d) {
                        return d.value;
                    })

                    // EXIT
                    var exitCirc = circ.exit();
                    exitCirc.transition().duration(250)
                        .attr("r", 0);

                }

                function render(data) {
                    data = ObjectService.construct(data, scope.attribute, scope.mess);

                    data = _.reject(data, function(d) {
                        return d.label === "NA";
                    });

                    var margin = {
                            top: 25,
                            right: 50,
                            bottom: 50,
                            left: 25
                        },
                        width = 1200 - margin.left - margin.right,
                        height = 200 - margin.top - margin.bottom;
                    var parseDate = d3.time.format("%b %Y").parse;

                    x = d3.time.scale().range([0, width - margin.left - margin.right])

                    var xAxis = d3.svg.axis().scale(x).orient("bottom")
                        .ticks(10)
                        .tickSize(-height, 0)
                        .tickFormat(d3.time.format("%m-%d-%y"));

                    x.domain(d3.extent(data.map(function(d) {
                        return getDate(d.label);
                    })));

                    var svg = d3.select(element[0]).append("svg")
                        .attr("width", width + margin.left + margin.right)
                        .attr("height", height + margin.top + margin.bottom);

                    context = svg.append("g")
                        .attr("class", "context")
                        .attr("transform", "translate(" + (margin.left + 50) + "," + (height / 2) + ")");

                    var ev = context.selectAll(".event")
                        .data(scope.events)
                        .enter().append("g")
                        .attr("transform", function(d) {
                            return d.date ? "translate(" + x(getDate(d.date)) + "," + margin.top + ")" : "translate(" + x(getDate(d.daterange[0])) + "," + margin.top + ")"
                        })

                    ev.append("rect")
                        .attr("class", "timeline-event")
                        .attr("y", -(height / 2) + margin.top)
                        .attr("height", height - 50)
                        .attr("width", 1);

                    context.selectAll(".circ")
                        .data(data)
                        .enter().append("circle")
                        .attr("class", "circ")
                        .attr("cx", function(d) {
                            return x(getDate(d.label));
                        })
                        .attr("cy", function(d, i) {
                            return circleSize * 2;
                        })
                        .on('click', function(d) {
                            console.log(d)
                        })
                        .attr("r", function(d) {
                            return Math.min(50, Math.max(10, 20 * Math.log(d.value)));
                        })
                        .append("svg:title").text(function(d) {
                            return d.value;
                        })

                    var textGr = ev.append("g")
                        .attr("transform", function(d, i) {
                            var dy = (i % 2) ? height / 2 : -height / 2;
                            return "translate(0," + dy + ")";
                        })

                    textGr.append("text")
                        .attr("font-size", 10)
                        .style("font-weight", 700)
                        .style("text-anchor", "middle")
                        .text(function(d) {
                            return d.name;
                        })

                    textGr.append("text")
                        .attr("font-size", 10)
                        .attr("dy", 12)
                        .style("text-anchor", "middle")
                        .text(function(d) {
                            var date = (d.date) ? d.date : d.daterange[0];
                            return date;
                        })

                }

                function getDate(date) {
                    return moment(date.trim(), "MM/DD/YYYY").valueOf();
                }
            }
        }
    }
]);
<commit_msg>Timeseries transition fixes<commit_after>angular.module('modelCompanyApp').
directive('timeseries', ['$window', 'ObjectService',
    function($window, ObjectService) {
        return {
            restrict: 'A',
            scope: {
                data: "=",
                events: "=",
                attribute: "@",
                filter: "=",
                mess: "@"
            },
            link: function(scope, element, attrs) {

                var context, x;
                var circleSize = 12;

                scope.$watch('data', function(newVal) {
                    if (newVal)
                        render(newVal);
                });

                scope.$watch('filter', function(newVal) {
                    if (context && newVal)
                        update(newVal)
                }, true)

                function update(filter) {

                    var data = ObjectService.constructWithFilter(scope.data, scope.attribute, filter);

                    // DATA JOIN
                    var circ = context.selectAll(".circ")
                        .data(data);

                    // UPDATE
                    circ.transition().duration(500)
                        .attr("r", function(d) {
                            return Math.min(50, Math.max(10, 20 * Math.log(d.value)));
                        })

                    circ.selectAll('title')
                        .text(function(d) {
                            return d.value;
                        })

                    // EXIT
                    var exitCirc = circ.exit();
                    exitCirc.transition().duration(250)
                        .attr("r", 0);

                }

                function render(data) {
                    data = ObjectService.construct(data, scope.attribute, scope.mess);

                    data = _.reject(data, function(d) {
                        return d.label === "NA";
                    });

                    var margin = {
                            top: 25,
                            right: 50,
                            bottom: 50,
                            left: 25
                        },
                        width = 1200 - margin.left - margin.right,
                        height = 200 - margin.top - margin.bottom;
                    var parseDate = d3.time.format("%b %Y").parse;

                    x = d3.time.scale().range([0, width - margin.left - margin.right])

                    var xAxis = d3.svg.axis().scale(x).orient("bottom")
                        .ticks(10)
                        .tickSize(-height, 0)
                        .tickFormat(d3.time.format("%m-%d-%y"));

                    x.domain(d3.extent(data.map(function(d) {
                        return getDate(d.label);
                    })));

                    var svg = d3.select(element[0]).append("svg")
                        .attr("width", width + margin.left + margin.right)
                        .attr("height", height + margin.top + margin.bottom);

                    context = svg.append("g")
                        .attr("class", "context")
                        .attr("transform", "translate(" + (margin.left + 50) + "," + (height / 2) + ")");

                    var ev = context.selectAll(".event")
                        .data(scope.events)
                        .enter().append("g")
                        .attr("transform", function(d) {
                            return d.date ? "translate(" + x(getDate(d.date)) + "," + margin.top + ")" : "translate(" + x(getDate(d.daterange[0])) + "," + margin.top + ")"
                        })

                    ev.append("rect")
                        .attr("class", "timeline-event")
                        .attr("y", -(height / 2) + margin.top)
                        .attr("height", height - 50)
                        .attr("width", "1px");

                    context.selectAll(".circ")
                        .data(data)
                        .enter().append("circle")
                        .attr("class", "circ")
                        .attr("cx", function(d) {
                            return x(getDate(d.label));
                        })
                        .attr("cy", function(d, i) {
                            return circleSize * 2;
                        })
                        .on('click', function(d) {
                            console.log(d)
                        })
                        .attr("r", function(d) {
                            return Math.min(50, Math.max(10, 20 * Math.log(d.value)));
                        })
                        .append("svg:title").text(function(d) {
                            return d.value;
                        })

                    var textGr = ev.append("g")
                        .attr("transform", function(d, i) {
                            var dy = (i % 2) ? height / 2 : -height / 2;
                            return "translate(0," + dy + ")";
                        })

                    textGr.append("text")
                        .attr("font-size", 10)
                        .style("font-weight", 700)
                        .style("text-anchor", "middle")
                        .text(function(d) {
                            return d.name;
                        })

                    textGr.append("text")
                        .attr("font-size", 10)
                        .attr("dy", 12)
                        .style("text-anchor", "middle")
                        .text(function(d) {
                            var date = (d.date) ? d.date : d.daterange[0];
                            return date;
                        })

                }

                function getDate(date) {
                    return moment(date.trim(), "MM/DD/YYYY").valueOf();
                }
            }
        }
    }
]);
<|endoftext|>


<commit_before>// Originally based on the Arecibo JavaScript client

if (Sentry === undefined) {
    var Sentry = {};
}
(function(){
    Sentry.client = {};

    var self = Sentry.client;

    Sentry.client.loaded = false;
    Sentry.client.options = {
        fetchHeaders: false,
        publicKey: null,
        server: '/sentry/store/', // JS client only supports a single server
        projectId: 1
    };

    Sentry.client.config = function(data){
        for (var k in data) {
            self.options[k] = data[k];
        }
    };

    Sentry.client.parseUrl = function(url) {
        var url_parts = url.split('?');
        var querystring = url_parts[1];

        return {
            url: url_parts[0],
            querystring: url_parts[1]
        };
    };

    Sentry.client.getHeaders = function() {
        if (self.options.fetchHeaders) {
            var req = new XMLHttpRequest();
            req.open('HEAD', document.location, false);
            req.send(null);
            headers = req.getAllResponseHeaders().toLowerCase();
        } else {
            headers = {
                "Referer": document.referrer,
                "User-Agent": navigator.userAgent
            };
        }
        return headers;
    };

    Sentry.client.addEvent = function(elem, event, func) {
        if (elem.addEventListener) {
            elem.addEventListener(event, func, false);
            return true;
        } else if (elem.attachEvent) {
            var result = elem.attachEvent("on"+event, func);
            return result;
        }
        return false;
    };

    Sentry.client.process = function(data) {
        data.project = self.options.projectId;

        var req = new XMLHttpRequest();
        // req.setRequestHeader('User-Agent', 'Sentry:JS/1.0');
        // req.setRequestHeader('Content-type', 'application/json');
        // req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        req.open('POST', self.options.server + '?project_id=' + self.options.projectId, false);
        console.log(JSON.stringify(data));
        req.send(JSON.stringify(data));
    };

    Sentry.client.captureException = function(e) {
        var lineno;
        var url;
        var traceback;
        var headers;
        var message = e.toString();

        if (e.line) { // WebKit
            lineno = e.line;
        } else if (e.lineNumber) { // Mozilla
            lineno = e.lineNumber;
        }

        if (e.sourceURL) { // Webkit
            url = e.sourceURL;
        } else if (e.fileName) { // Mozilla
            url = e.fileName;
        } else {
            url = window.location;
        }

        // Currently Mozilla only:
        if (e.stack) {
            traceback = e.stack;
        }

        var urlparts = self.parseUrl(url);

        var data = {
            "message": e.name + ": " + message,
            // "sentry.interfaces.Stacktrace": {
            //     "frames": [
            //         {
            //             "lineno": lineno
            //         }
            //     ]
            // },
            "sentry.interfaces.Exception": {
                "type": e.name,
                "value": message
            },
            "sentry.interfaces.Http": {
                "url": urlparts.url,
                "querystring": urlparts.querystring,
                "headers": self.getHeaders()
            }
        };

        self.process(data);
    };

    Sentry.client.registerGlobalHandler = function() {
        /*
            NOTE: Currently this will only work on Firefox and Internet Explorer.

            Safari and Chrome have open feature requests for global error handlers:

            https://bugs.webkit.org/show_bug.cgi?id=8519
            http://code.google.com/p/chromium/issues/detail?id=7771
        */

        window.onerror = function(message, url, lineno, stack) {
            var urlparts = self.parseUrl(url);
            var data = {
                "message": message,
                // "sentry.interfaces.Stacktrace": {
                //     "frames": [
                //         {
                //             "lineno": lineno
                //         }
                //     ]
                // },
                "sentry.interfaces.Exception": {
                    "value": message
                },
                "sentry.interfaces.Http": {
                    "url": urlparts.url,
                    "querystring": urlparts.querystring,
                    "headers": self.getHeaders()
                }
            };
            self.process(data);
        };
    };
}());<commit_msg>Default logger of javascript for js client<commit_after>// Originally based on the Arecibo JavaScript client

if (Sentry === undefined) {
    var Sentry = {};
}
(function(){
    Sentry.client = {};

    var self = Sentry.client;

    Sentry.client.loaded = false;
    Sentry.client.options = {
        fetchHeaders: false,
        publicKey: null,
        server: '/sentry/store/', // JS client only supports a single server
        projectId: 1,
        logger: 'javascript'
    };

    Sentry.client.config = function(data){
        for (var k in data) {
            self.options[k] = data[k];
        }
    };

    Sentry.client.parseUrl = function(url) {
        var url_parts = url.split('?');
        var querystring = url_parts[1];

        return {
            url: url_parts[0],
            querystring: url_parts[1]
        };
    };

    Sentry.client.getHeaders = function() {
        if (self.options.fetchHeaders) {
            var req = new XMLHttpRequest();
            req.open('HEAD', document.location, false);
            req.send(null);
            headers = req.getAllResponseHeaders().toLowerCase();
        } else {
            headers = {
                "Referer": document.referrer,
                "User-Agent": navigator.userAgent
            };
        }
        return headers;
    };

    Sentry.client.addEvent = function(elem, event, func) {
        if (elem.addEventListener) {
            elem.addEventListener(event, func, false);
            return true;
        } else if (elem.attachEvent) {
            var result = elem.attachEvent("on"+event, func);
            return result;
        }
        return false;
    };

    Sentry.client.process = function(data) {
        data.project = self.options.projectId;
        data.logger = self.options.logger;

        var req = new XMLHttpRequest();
        // req.setRequestHeader('User-Agent', 'Sentry:JS/1.0');
        // req.setRequestHeader('Content-type', 'application/json');
        // req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        req.open('POST', self.options.server + '?project_id=' + self.options.projectId, false);
        console.log(JSON.stringify(data));
        req.send(JSON.stringify(data));
    };

    Sentry.client.captureException = function(e) {
        var lineno;
        var url;
        var traceback;
        var headers;
        var message = e.toString();

        if (e.line) { // WebKit
            lineno = e.line;
        } else if (e.lineNumber) { // Mozilla
            lineno = e.lineNumber;
        }

        if (e.sourceURL) { // Webkit
            url = e.sourceURL;
        } else if (e.fileName) { // Mozilla
            url = e.fileName;
        } else {
            url = window.location;
        }

        // Currently Mozilla only:
        if (e.stack) {
            traceback = e.stack;
        }

        var urlparts = self.parseUrl(url);

        var data = {
            "message": e.name + ": " + message,
            // "sentry.interfaces.Stacktrace": {
            //     "frames": [
            //         {
            //             "lineno": lineno
            //         }
            //     ]
            // },
            "sentry.interfaces.Exception": {
                "type": e.name,
                "value": message
            },
            "sentry.interfaces.Http": {
                "url": urlparts.url,
                "querystring": urlparts.querystring,
                "headers": self.getHeaders()
            }
        };

        self.process(data);
    };

    Sentry.client.registerGlobalHandler = function() {
        /*
            NOTE: Currently this will only work on Firefox and Internet Explorer.

            Safari and Chrome have open feature requests for global error handlers:

            https://bugs.webkit.org/show_bug.cgi?id=8519
            http://code.google.com/p/chromium/issues/detail?id=7771
        */

        window.onerror = function(message, url, lineno, stack) {
            var urlparts = self.parseUrl(url);
            var data = {
                "message": message,
                // "sentry.interfaces.Stacktrace": {
                //     "frames": [
                //         {
                //             "lineno": lineno
                //         }
                //     ]
                // },
                "sentry.interfaces.Exception": {
                    "value": message
                },
                "sentry.interfaces.Http": {
                    "url": urlparts.url,
                    "querystring": urlparts.querystring,
                    "headers": self.getHeaders()
                }
            };
            self.process(data);
        };
    };
}());<|endoftext|>


<commit_before>import {dbconnectionManager} from './DBConnectionManager';
import {blockChainVerifier} from './BlockChainVerifier';
import { observable} from 'mobx';

class TransactionHelper {

    constructor() {}

    getTransactionById(transId, callback) {
        let result = dbconnectionManager.getConnection().collection('Transactions').findOne({
                "id": transId
            }).then((result) => {
                if (result) {
                    callback(null, result);
                }
                else {
                    callback(null, false);
                }
            })
            .catch((err) => {
                console.error("Error occurred while fetching transaction by tnxId." + err);
                callback(err, null);
            });
    }

    getTransactionByBusinessTransactionId(btId, callback) {
        let result = dbconnectionManager.getConnection().collection('Transactions').find({
            "transactionSliceObjects": {
                $elemMatch: {
                    "businessTransactions": {
                        $elemMatch: {
                            "btid": {$in : btId}
                        }
                    }
                }
            }
        }).sort({date:-1}).toArray(function(err, result) {
            if (err) {
                console.error("Error occurred while fetching transaction by btId." + err);
                callback(err, null);
            } else {
                callback(null, result);
            }
        });
    }

    getTransactionByText(searchText, callback) {
        let result = dbconnectionManager.getConnection().collection('Transactions').find({
        $text: {$search: searchText}},{score: {$meta: "textScore"}})
            .sort({score:{$meta:"textScore"}
           }).toArray(function(err, result) {
            if (err) {
                console.error("Error occurred while fetching transations by text." + err);
                callback(err, null);
            } else {
                callback(null, result);
            }
        });
    }

    getTransactionByIds(transIds, callback) {
        let result = dbconnectionManager.getConnection().collection('Transactions').find({
             "id": { $in: transIds},
            }).toArray(function(err, result) {
                if (err) {
                    console.error("Error occurred while fetching transaction by getTransactionByIds." + err);
                    callback(err, null);
                } else {
                    callback(null, result);
                }
            });
    }

    /**
     * returns a map(Actual Map object) of
     * <transaction.id>_<ent_name> : <stringified version of the slice>
     * @param {*} transactions - list of slice objects which include my ent view and all others (full payload)
     * @param {*} myEntName - name of the logged enterprise
     */
    extractSlicesToVerify(transactions, myEntName) {
        let verificationPairs = new Map();
        transactions.forEach(transaction => {
            if (transaction) {
                for (let j = 0; j < transaction.transactionSliceObjects.length; j++) {
                    let tnxSliceObj = transaction.transactionSliceObjects[j];
                    let tnxSliceStringified = transaction.transactionSlices[j];

                    if (tnxSliceObj.type == "Enterprise" && tnxSliceObj.enterprise == myEntName) {
                        verificationPairs.set(transaction.id + "_" + myEntName, tnxSliceStringified);
                    }

                    if (tnxSliceObj.type == "Intersection" && ((tnxSliceObj.enterprises).indexOf(myEntName) > -1)) {
                        let logInUserEntIndex = (tnxSliceObj.enterprises).indexOf(myEntName);
                        let partnerEntName = logInUserEntIndex == 0 ? tnxSliceObj.enterprises[1] : tnxSliceObj.enterprises[0];
                        verificationPairs.set(transaction.id + "_" + partnerEntName, tnxSliceStringified);
                    }
                }
            }
        });
        return verificationPairs;
    }

    saveBlockChainSettings(config, callback) {
    // check if there is any saved value
        dbconnectionManager.getConnection().collection('Settings').findOne({ type: 'applicationSettings' }, function (err, exist) {
            if (err) {
                logger.error(err);
                callback(err, false);
            }

            if (exist && exist.blockChain) {
                callback(null, true);
            } else {
                //make sure the inserted values are not null
                // if (config.constructor !== Object) {
                //     callback(null, false);
                // }
                // if (Object.keys(config).length === 0) {
                //     callback(null, false);
                // }
                let data = '';
                if(exist && exist.chainOfCustidy) {
                    exist.blockChain= {
                        'url': config.url,
                        'contractAddress': config.contractAddress,
                        'privateKey': config.privatekey
                    }
                    data = exist;
                } else {
                    data = {
                        type: 'applicationSettings',
                        blockChain: {
                            'url': config.url,
                            'contractAddress': config.contractAddress,
                            'privateKey': config.privatekey
                        }

                    };
                }

                var result = dbconnectionManager.getConnection().collection('Settings').update({ type: 'applicationSettings' }, data, { upsert: true }).then(function (result) {
                    if (result) {
                        callback(null, true);
                    }
                }).catch(function (err) {
                    console.error("Error occurred while saving configuration to database." + err);
                    callback(err, false);
                });
            }
        });
    }

    findSliceInTransaction(transaction, transactionSlice,callback) {
        let tranSliceObj = JSON.parse(transactionSlice);
        let transactionSliceObjects = transaction.transactionSliceObjects;
        let sliceIndex = null;
        for (let index = 0; index < transactionSliceObjects.length; index++) {
            if (transactionSliceObjects[index].type == "Enterprise" &&
                tranSliceObj.type == transactionSliceObjects[index].type) {
                sliceIndex = index;
                break;
            } else if (transactionSliceObjects[index].type == "Intersection" &&
                (transactionSliceObjects[index].enterprises.indexOf(tranSliceObj.enterprises[0]) > -1 &&
                    transactionSliceObjects[index].enterprises.indexOf(tranSliceObj.enterprises[1]) > -1)) {
                sliceIndex = index;
                break;
            }
        }
        return sliceIndex;
    }

    storeVerificationData(transactions, entNameOfLoggedUser, oneBcClient) {
        let verifications = observable.map({});
        let verificationPairs = this.extractSlicesToVerify(transactions, entNameOfLoggedUser);
        verificationPairs.forEach((stringifiedSlice, key) => {
            verifications.set(key, undefined);
            blockChainVerifier.verifyBlockChain(stringifiedSlice, oneBcClient)
                .then(function (result) {
                    verifications.set(key, result === true ? 'verified' : 'failed');
                })
                .catch(function (error) {
                    // can give some error here
                    verifications.set(key, 'failed');
                });
        });
        return verifications;
    }
}

export const transactionHelper = new TransactionHelper();<commit_msg>missed checkin by pdubey<commit_after>import {dbconnectionManager} from './DBConnectionManager';
import {blockChainVerifier} from './BlockChainVerifier';
import { observable} from 'mobx';

class TransactionHelper {

    constructor() {}

    getTransactionById(transId, callback) {
        let result = dbconnectionManager.getConnection().collection('Transactions').findOne({
                "id": transId
            }).then((result) => {
                callback(null, result);
            })
            .catch((err) => {
                console.error("Error occurred while fetching transaction by tnxId." + err);
                callback(err, null);
            });
    }

    getTransactionByBusinessTransactionId(btId, callback) {
        let result = dbconnectionManager.getConnection().collection('Transactions').find({
            "transactionSliceObjects": {
                $elemMatch: {
                    "businessTransactions": {
                        $elemMatch: {
                            "btid": {$in : btId}
                        }
                    }
                }
            }
        }).sort({date:-1}).toArray(function(err, result) {
            if (err) {
                console.error("Error occurred while fetching transaction by btId." + err);
                callback(err, null);
            } else {
                callback(null, result);
            }
        });
    }

    getTransactionByText(searchText, callback) {
        let result = dbconnectionManager.getConnection().collection('Transactions').find({
        $text: {$search: searchText}},{score: {$meta: "textScore"}})
            .sort({score:{$meta:"textScore"}
           }).toArray(function(err, result) {
            if (err) {
                console.error("Error occurred while fetching transations by text." + err);
                callback(err, null);
            } else {
                callback(null, result);
            }
        });
    }

    getTransactionByIds(transIds, callback) {
        let result = dbconnectionManager.getConnection().collection('Transactions').find({
             "id": { $in: transIds},
            }).toArray(function(err, result) {
                if (err) {
                    console.error("Error occurred while fetching transaction by getTransactionByIds." + err);
                    callback(err, null);
                } else {
                    callback(null, result);
                }
            });
    }

    /**
     * returns a map(Actual Map object) of
     * <transaction.id>_<ent_name> : <stringified version of the slice>
     * @param {*} transactions - list of slice objects which include my ent view and all others (full payload)
     * @param {*} myEntName - name of the logged enterprise
     */
    extractSlicesToVerify(transactions, myEntName) {
        let verificationPairs = new Map();
        transactions.forEach(transaction => {
            if (transaction) {
                for (let j = 0; j < transaction.transactionSliceObjects.length; j++) {
                    let tnxSliceObj = transaction.transactionSliceObjects[j];
                    let tnxSliceStringified = transaction.transactionSlices[j];

                    if (tnxSliceObj.type == "Enterprise" && tnxSliceObj.enterprise == myEntName) {
                        verificationPairs.set(transaction.id + "_" + myEntName, tnxSliceStringified);
                    }

                    if (tnxSliceObj.type == "Intersection" && ((tnxSliceObj.enterprises).indexOf(myEntName) > -1)) {
                        let logInUserEntIndex = (tnxSliceObj.enterprises).indexOf(myEntName);
                        let partnerEntName = logInUserEntIndex == 0 ? tnxSliceObj.enterprises[1] : tnxSliceObj.enterprises[0];
                        verificationPairs.set(transaction.id + "_" + partnerEntName, tnxSliceStringified);
                    }
                }
            }
        });
        return verificationPairs;
    }

    saveBlockChainSettings(config, callback) {
    // check if there is any saved value
        dbconnectionManager.getConnection().collection('Settings').findOne({ type: 'applicationSettings' }, function (err, exist) {
            if (err) {
                logger.error(err);
                callback(err, false);
            }

            if (exist && exist.blockChain) {
                callback(null, true);
            } else {
                //make sure the inserted values are not null
                // if (config.constructor !== Object) {
                //     callback(null, false);
                // }
                // if (Object.keys(config).length === 0) {
                //     callback(null, false);
                // }
                let data = '';
                if(exist && exist.chainOfCustidy) {
                    exist.blockChain= {
                        'url': config.url,
                        'contractAddress': config.contractAddress,
                        'privateKey': config.privatekey
                    }
                    data = exist;
                } else {
                    data = {
                        type: 'applicationSettings',
                        blockChain: {
                            'url': config.url,
                            'contractAddress': config.contractAddress,
                            'privateKey': config.privatekey
                        }

                    };
                }

                var result = dbconnectionManager.getConnection().collection('Settings').update({ type: 'applicationSettings' }, data, { upsert: true }).then(function (result) {
                    if (result) {
                        callback(null, true);
                    }
                }).catch(function (err) {
                    console.error("Error occurred while saving configuration to database." + err);
                    callback(err, false);
                });
            }
        });
    }

    findSliceInTransaction(transaction, transactionSlice,callback) {
        let tranSliceObj = JSON.parse(transactionSlice);
        let transactionSliceObjects = transaction.transactionSliceObjects;
        let sliceIndex = null;
        for (let index = 0; index < transactionSliceObjects.length; index++) {
            if (transactionSliceObjects[index].type == "Enterprise" &&
                tranSliceObj.type == transactionSliceObjects[index].type) {
                sliceIndex = index;
                break;
            } else if (transactionSliceObjects[index].type == "Intersection" &&
                (transactionSliceObjects[index].enterprises.indexOf(tranSliceObj.enterprises[0]) > -1 &&
                    transactionSliceObjects[index].enterprises.indexOf(tranSliceObj.enterprises[1]) > -1)) {
                sliceIndex = index;
                break;
            }
        }
        return sliceIndex;
    }

    storeVerificationData(transactions, entNameOfLoggedUser, oneBcClient) {
        let verifications = observable.map({});
        let verificationPairs = this.extractSlicesToVerify(transactions, entNameOfLoggedUser);
        verificationPairs.forEach((stringifiedSlice, key) => {
            verifications.set(key, undefined);
            blockChainVerifier.verifyBlockChain(stringifiedSlice, oneBcClient)
                .then(function (result) {
                    verifications.set(key, result === true ? 'verified' : 'failed');
                })
                .catch(function (error) {
                    // can give some error here
                    verifications.set(key, 'failed');
                });
        });
        return verifications;
    }
}

export const transactionHelper = new TransactionHelper();<|endoftext|>


<commit_before>var utils = require('./utils'),
    defaultChannel = '/system',
    Q = require('q'),
    _ = require('underscore');

var data = require('../../data');

function loadMapByKey(key) {
    var defer = Q.defer();

    data.map.findMapByKey(key)
        .then(function(map){

            // load online heroes
            data.hero.findOnlineHeroesForMap(key)
                .then(function(heroes){

                    map.onlineHeroes = heroes;
                    var itemIds = _.chain(map.mapObjects).filter(function(mapObject){
                        return true;
                    }).pluck('itemId').vlue();

                    // load items on map
                    return data.item.findItemsByKeys(itemIds)
                        .then(function(items){

                            // load items
                            var itemsOnMap = [];
                            items.forEach(function(item){
                                var positionData = _.find(map.mapObjects, function(obj){
                                    return obj.type === 'item' && obj.itemId === item.key;
                                });

                                var builtItem = _.omit(item, []);
                                builtItem.position = positionData.position;

                                itemsOnMap.push(builtItem);
                            });

                            map.itemsOnMap = itemsOnMap;
                        });
                })
                .fail(function(err){
                    defer.reject(err);
                })
                .done(function(){
                    defer.resolve(map);
                });
        });

    return defer.promise;
}

var onUserLogin = utils.wrapWithPromise(function (gameEvent, deferred) {
    // eventData: username, password

    var eventData = {},
        errorEncountered = null;
    data.user.registerUser(gameEvent.data)

        // get user object
        .then(function(registeredUser){
            eventData.user = {
                username: registeredUser.username
            };

            return data.hero.createHero({
                username: registeredUser.username,
                name: registeredUser.username,
                status: 'online'
            });
        })

        // get hero
        .then(function(createdHero){
            eventData.hero = createdHero;
            return loadMapByKey(createdHero.position.map);
        })

        // load map based on hero position
        .then(function(map){
            eventData.map = map;
        })

        // forward any errors back
        .fail(function(error){
            errorEncountered = error;
            deferred.reject(error);
        })

        // return event
        .done(function(){
            // console.log(eventData);
            if (!errorEncountered) {
                // mark images / assets that need loading
                eventData.images = {
                    "heroSprite": eventData.hero.heroSprite,
                    "tileSet": eventData.map.tileSet
                };

                deferred.resolve(utils.createGameEvent(defaultChannel, 'userLoggedIn', eventData));
            }
        });
});

function sendLogoutEvent(gameEvent, deferred) {
    console.log('User logged out', gameEvent);
    // notify other clients that user has logged out
    deferred.resolve(utils.createGameEvent(defaultChannel, 'userLoggedOut', gameEvent.data));
}

var onUserLogout = utils.wrapWithPromise(function (gameEvent, deferred) {

    // eventData: username, hero_id
    data.hero.setHeroStatus(gameEvent.data.hero_id, 'offline')
        .fail(function(err){
            // logout user anyway
            sendLogoutEvent(gameEvent, deferred);
        })
        .done(function(){
            // notify other clients that user has logged out
            sendLogoutEvent(gameEvent, deferred);
        });

});

module.exports = {
    onUserLogin: onUserLogin,
    onUserLogout: onUserLogout
};<commit_msg>Missed 'a' in value on line 19.<commit_after>var utils = require('./utils'),
    defaultChannel = '/system',
    Q = require('q'),
    _ = require('underscore');

var data = require('../../data');

function loadMapByKey(key) {
    var defer = Q.defer();

    data.map.findMapByKey(key)
        .then(function(map){
            // load online heroes
            data.hero.findOnlineHeroesForMap(key)
                .then(function(heroes){
                    map.onlineHeroes = heroes;
                    var itemIds = _.chain(map.mapObjects).filter(function(mapObject){
                        return true;
                    }).pluck('itemId').value();

                    // load items on map
                    return data.item.findItemsByKeys(itemIds)
                        .then(function(items){

                            // load items
                            var itemsOnMap = [];
                            items.forEach(function(item){
                                var positionData = _.find(map.mapObjects, function(obj){
                                    return obj.type === 'item' && obj.itemId === item.key;
                                });

                                var builtItem = _.omit(item, []);
                                builtItem.position = positionData.position;

                                itemsOnMap.push(builtItem);
                            });

                            map.itemsOnMap = itemsOnMap;
                        });
                })
                .fail(function(err){
                    defer.reject(err);
                })
                .done(function(){
                    defer.resolve(map);
                });
        });

    return defer.promise;
}

var onUserLogin = utils.wrapWithPromise(function (gameEvent, deferred) {
    // eventData: username, password

    var eventData = {},
        errorEncountered = null;
    data.user.registerUser(gameEvent.data)

        // get user object
        .then(function(registeredUser){
            eventData.user = {
                username: registeredUser.username
            };

            return data.hero.createHero({
                username: registeredUser.username,
                name: registeredUser.username,
                status: 'online'
            });
        })

        // get hero
        .then(function(createdHero){
            eventData.hero = createdHero;
            return loadMapByKey(createdHero.position.map);
        })

        // load map based on hero position
        .then(function(map){
            eventData.map = map;
        })

        // forward any errors back
        .fail(function(error){
            errorEncountered = error;
            deferred.reject(error);
        })

        // return event
        .done(function(){
            // console.log(eventData);
            if (!errorEncountered) {
                // mark images / assets that need loading
                eventData.images = {
                    "heroSprite": eventData.hero.heroSprite,
                    "tileSet": eventData.map.tileSet
                };

                deferred.resolve(utils.createGameEvent(defaultChannel, 'userLoggedIn', eventData));
            }
        });
});

function sendLogoutEvent(gameEvent, deferred) {
    console.log('User logged out', gameEvent);
    // notify other clients that user has logged out
    deferred.resolve(utils.createGameEvent(defaultChannel, 'userLoggedOut', gameEvent.data));
}

var onUserLogout = utils.wrapWithPromise(function (gameEvent, deferred) {

    // eventData: username, hero_id
    data.hero.setHeroStatus(gameEvent.data.hero_id, 'offline')
        .fail(function(err){
            // logout user anyway
            sendLogoutEvent(gameEvent, deferred);
        })
        .done(function(){
            // notify other clients that user has logged out
            sendLogoutEvent(gameEvent, deferred);
        });

});

module.exports = {
    onUserLogin: onUserLogin,
    onUserLogout: onUserLogout
};<|endoftext|>


<commit_before>/*******************************************************************************
 * @license
 * Copyright (c) 2012 VMware, Inc. All Rights Reserved.
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Contributors:
 *     Kris De Volder - initial API and implementation
 ******************************************************************************/

/*global console exports require*/

var getDirectory = require('./utils').getDirectory;
var orMap = require('./utils').orMap;
var pathResolve = require('./utils').pathResolve;
var jsonMerge = require('./json-merge');
var defaults = require('./dot-scripted-defaults');
var when = require('when');
var pipeline = require('when/pipeline');

var JSON5 = require('json5');

function debug_log(msg) {
//	console.log(msg);
}

function configure(filesystem) {

	var MAIN_SCRIPTED_RC_FILE = 'scripted.json';

	var listFiles = filesystem.listFiles;
	var getContents = filesystem.getContents;
	var getUserHome = filesystem.getUserHome;
	var isFile = filesystem.isFile;
	var isDirectory = filesystem.isDirectory;
	var putContents = filesystem.putContents;
	var handle2file = filesystem.handle2file;
	var stat = filesystem.stat;
	var mkdir = filesystem.mkdir;
	var deleteResource = filesystem.deleteResource;

	// For a given file handle the '.scripted' configuration info is found and composed as follows:

	// 1) find the corresponding rootDir. This is closest directory in the path to the file
	//    that contains a rootMarkerFile.
	// 2) if the rootDir has a .scripted file read its JSON data
	//  2.b) add the rootdir to the parsed data as a property 'fsroot'
	// 3) read the '.scriptedrc' file in the user's home directory.
	// 4) merge the data from both where '.scriptedrc' has lower priority than '.scripted'
	//    for any properties that are contained in both.

	function isRootMarkerFile(name) {
		if (name==='.scripted' || name==='.project' || name==='.git') {
			return name;
		}
	}

	/**
	 * Find the root dir associated with a given file handle. This is the closest directory
	 * on the path that contains a root marker file.
	 *

	 * If no directory on any of the parent directories contains a root marker file, then
	 * this function will return a falsy value.
	 */
	function getRootDir(dir, callback) {
		if (dir) {
			listFiles(dir,
				function (names) {
					var rootMarkerName = orMap(names, isRootMarkerFile);
					if (rootMarkerName) {
						callback(dir);
					} else {
						getRootDir(getDirectory(dir), callback);
					}
				}
			);
		} else {
			callback(false);
		}
	}

	var ALL_WHITE_SPACE = /^\s*$/;

	/**
	 * Tries to read data from a file and parse it as JSON data.
	 * Call the callback with the resulting data.
	 * If any part of this operation fails, the callback will be still be
	 * called with at least an empty object. All errors will be logged
	 * to the console.
	 *

	 * Errors deemed serious enough to be brought to the user's attention
	 * (i.e. problems parsing the user's config file) will be 'reported'
	 * by adding an explanation to the object in a property called 'error'.
	 */
	function parseJsonFile(handle, callback) {
		getContents(handle,
			function (contents) {
				var data = null;
				if (!ALL_WHITE_SPACE.test(contents)) {
					try {
						data = JSON5.parse(contents);
					} catch (e) {
						data = {
							error: "Couldn't parse (JSON5) '"+handle+"'\nERROR: " + e
						};
					}
				}
				data = data || {};
				return callback(data);
			},
			function (err) {
				debug_log(err);
				callback({
					//Don't report this as user-level error. Some people simply don't have a .scripted or .scriptedrc
					//so this error is expected.
					//error: "Could not get contents of file '"+handle+"'"
				});
			}
		);
	}

	function findAndParseDotScripted(handle, callback) {
		getRootDir(handle, function (root) {
			root = root || getDirectory(handle);
			if (!root) {
				return callback({});
			} else {
				var dotScriptedFile = pathResolve(root, '.scripted');

				parseJsonFile(dotScriptedFile, function (dotScripted) {
					dotScripted.fsroot = root;
					callback(dotScripted);
				});
			}
		});
	}

	function findAndParseScriptedRc(callback) {
		var home = getUserHome();
		if (home) {
			var configFile = pathResolve(home, ".scriptedrc");
			return isDirectory(configFile, function (isDir) {
				if (isDir) {
					configFile = pathResolve(configFile, MAIN_SCRIPTED_RC_FILE);
				}
				return parseJsonFile(configFile, callback);
			});
		} else {
			return callback({});
		}
	}

	/**
	 * Retrieve the scripted configuration data for a given file or directory.
	 * Ideally anybody interested in the '.scripted' configuration data
	 * should be using this method and this method alone to retrieve the config info.
	 * This to ensure that all share the same logic of retrieving this data.
	 * This will make it easier in the future to change how and where this data is
	 * loaded.
	 *
	 * The returned config object may contain an 'error' property if there was a
	 * problem reading/parsing some or all of the configuration data.
	 */
	function getConfiguration(handle, callback) {
		findAndParseDotScripted(handle, function (dotScripted) {
			findAndParseScriptedRc(function (scriptedRc) {
				console.log(JSON.stringify(scriptedRc));
				console.log(JSON.stringify(dotScripted));
				callback(jsonMerge(defaults, scriptedRc, dotScripted));
			});
		});
	}

	function getScriptedRcDirLocation() {
		var home = getUserHome();
		if (home) {
			var configFile = pathResolve(home, '.scriptedrc');
			return configFile;
		}
		//return undefined;
	}

	function getScriptedRcFileLocation(name) {
		var configDir = getScriptedRcDirLocation();
		if (configDir) {
			var configFile = pathResolve(configDir, name+'.json');
			return configFile;
		}
		//return undefined;
	}

	/**
	 * Gets a given config file from the .scriptedrc folder in the user.home directort
	 * @return {Promise}
	 */
	function getScriptedRcFile(name) {
		debug_log('scriptedrc file requested: '+name);
		var d = when.defer();
		var configFile = getScriptedRcFileLocation(name);
		debug_log('scriptedrc file path = '+configFile);
		if (configFile) {
			parseJsonFile(configFile, function (jsonData) {
				d.resolve(jsonData);
			});
		} else {
			d.resolve({});
		}
		return d;
	}

	function convertRcFileToDir(loc) {
		return getContents(loc).then(function (contents) {
			debug_log('got contents of ' + loc );
			debug_log(contents);
			return pipeline([
				function () {
					debug_log('Deleting ...');
					return deleteResource(loc).then(function () {
						debug_log('Deleting OK');
					});
				},
				function () {
					debug_log('Mkdir '+loc+' ...');
					return mkdir(loc).then(function () {
						debug_log('Mkdir OK');
					});
				},
				function () {
					var putLoc = pathResolve(loc, MAIN_SCRIPTED_RC_FILE);
					debug_log('putting contents to '+putLoc+' ...');
					return putContents(putLoc, contents).then(function () {
						debug_log('putting OK');
					});
				}
			]);
		});
	}

	/**
	 * Ensures that .scriptedrc is in directory format. If it isn't yet...
	 * then migrate it.
	 */
	function ensureDirectoryForm() {
		debug_log('ensure directory form');
		var loc = getScriptedRcDirLocation();
		return stat(loc).then(
			function (s) {
				if (s.isDirectory) {
					debug_log('Already a dir => DONE');
					//okay!
				} else if (s.isFile) {
					debug_log('It is a file');
					return convertRcFileToDir(loc);
				}
			},
			function (err) {
				//probably means file/dir doesn't exist. So create it.
				return mkdir(loc);
			}
		);
	}

	function putScriptedRcFile(name, contents) {
		return when(ensureDirectoryForm(), function () {
			debug_log('putScriptedRcFile: '+ name);
			debug_log(JSON.stringify(contents, null, '  '));
			var loc = getScriptedRcFileLocation(name);
			return putContents(loc, JSON.stringify(contents, null, '  '));
		});
	}

	return {
		getConfiguration: getConfiguration,
		getScriptedRcFile: getScriptedRcFile,
		putScriptedRcFile: putScriptedRcFile
	};

}

exports.configure = configure;
<commit_msg>Promisify 'parseJsonFile' in dot-scripted.js<commit_after>/*******************************************************************************
 * @license
 * Copyright (c) 2012 VMware, Inc. All Rights Reserved.
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Contributors:
 *     Kris De Volder - initial API and implementation
 ******************************************************************************/

/*global console exports require*/

var getDirectory = require('./utils').getDirectory;
var orMap = require('./utils').orMap;
var pathResolve = require('./utils').pathResolve;
var jsonMerge = require('./json-merge');
var defaults = require('./dot-scripted-defaults');
var when = require('when');
var pipeline = require('when/pipeline');

var JSON5 = require('json5');

function debug_log(msg) {
//	console.log(msg);
}

function configure(filesystem) {

	var MAIN_SCRIPTED_RC_FILE = 'scripted.json';

	var listFiles = filesystem.listFiles;
	var getContents = filesystem.getContents;
	var getUserHome = filesystem.getUserHome;
	var isFile = filesystem.isFile;
	var isDirectory = filesystem.isDirectory;
	var putContents = filesystem.putContents;
	var handle2file = filesystem.handle2file;
	var stat = filesystem.stat;
	var mkdir = filesystem.mkdir;
	var deleteResource = filesystem.deleteResource;

	// For a given file handle the '.scripted' configuration info is found and composed as follows:

	// 1) find the corresponding rootDir. This is closest directory in the path to the file
	//    that contains a rootMarkerFile.
	// 2) if the rootDir has a .scripted file read its JSON data
	//  2.b) add the rootdir to the parsed data as a property 'fsroot'
	// 3) read the '.scriptedrc' file in the user's home directory.
	// 4) merge the data from both where '.scriptedrc' has lower priority than '.scripted'
	//    for any properties that are contained in both.

	function isRootMarkerFile(name) {
		if (name==='.scripted' || name==='.project' || name==='.git') {
			return name;
		}
	}

	/**
	 * Find the root dir associated with a given file handle. This is the closest directory
	 * on the path that contains a root marker file.
	 *

	 * If no directory on any of the parent directories contains a root marker file, then
	 * this function will return a falsy value.
	 */
	function getRootDir(dir, callback) {
		if (dir) {
			listFiles(dir,
				function (names) {
					var rootMarkerName = orMap(names, isRootMarkerFile);
					if (rootMarkerName) {
						callback(dir);
					} else {
						getRootDir(getDirectory(dir), callback);
					}
				}
			);
		} else {
			callback(false);
		}
	}

	var ALL_WHITE_SPACE = /^\s*$/;

	/**
	 * Tries to read data from a file and parse it as JSON data.
	 * Call the callback with the resulting data.
	 * If any part of this operation fails, the callback will be still be
	 * called with at least an empty object. All errors will be logged
	 * to the console.
	 *

	 * Errors deemed serious enough to be brought to the user's attention
	 * (i.e. problems parsing the user's config file) will be 'reported'
	 * by adding an explanation to the object in a property called 'error'.
	 */
	function parseJsonFile(handle, callback) {
		var d;
		if (!callback) {
			d = when.defer();
			callback = function (result) {
				d.resolve(result);
			};
		}
		getContents(handle,
			function (contents) {
				var data = null;
				if (!ALL_WHITE_SPACE.test(contents)) {
					try {
						data = JSON5.parse(contents);
					} catch (e) {
						data = {
							error: "Couldn't parse (JSON5) '"+handle+"'\nERROR: " + e
						};
					}
				}
				data = data || {};
				return callback(data);
			},
			function (err) {
				debug_log(err);
				callback({
					//Don't report this as user-level error. Some people simply don't have a .scripted or .scriptedrc
					//so this error is expected.
					//error: "Could not get contents of file '"+handle+"'"
				});
			}
		);
		return d;
	}

	function findAndParseDotScripted(handle, callback) {
		getRootDir(handle, function (root) {
			root = root || getDirectory(handle);
			if (!root) {
				return callback({});
			} else {
				var dotScriptedFile = pathResolve(root, '.scripted');

				parseJsonFile(dotScriptedFile, function (dotScripted) {
					dotScripted.fsroot = root;
					callback(dotScripted);
				});
			}
		});
	}

	function findAndParseScriptedRc(callback) {
		var home = getUserHome();
		if (home) {
			var configFile = pathResolve(home, ".scriptedrc");
			return isDirectory(configFile, function (isDir) {
				if (isDir) {
					configFile = pathResolve(configFile, MAIN_SCRIPTED_RC_FILE);
				}
				return parseJsonFile(configFile, callback);
			});
		} else {
			return callback({});
		}
	}

	/**
	 * Retrieve the scripted configuration data for a given file or directory.
	 * Ideally anybody interested in the '.scripted' configuration data
	 * should be using this method and this method alone to retrieve the config info.
	 * This to ensure that all share the same logic of retrieving this data.
	 * This will make it easier in the future to change how and where this data is
	 * loaded.
	 *
	 * The returned config object may contain an 'error' property if there was a
	 * problem reading/parsing some or all of the configuration data.
	 */
	function getConfiguration(handle, callback) {
		findAndParseDotScripted(handle, function (dotScripted) {
			findAndParseScriptedRc(function (scriptedRc) {
				console.log(JSON.stringify(scriptedRc));
				console.log(JSON.stringify(dotScripted));
				callback(jsonMerge(defaults, scriptedRc, dotScripted));
			});
		});
	}

	function getScriptedRcDirLocation() {
		var home = getUserHome();
		if (home) {
			var configFile = pathResolve(home, '.scriptedrc');
			return configFile;
		}
		//return undefined;
	}

	function getScriptedRcFileLocation(name) {
		var configDir = getScriptedRcDirLocation();
		if (configDir) {
			var configFile = pathResolve(configDir, name+'.json');
			return configFile;
		}
		//return undefined;
	}

	/**
	 * Gets a given config file from the .scriptedrc folder in the user.home directort
	 * @return {Promise}
	 */
	function getScriptedRcFile(name) {
		debug_log('scriptedrc file requested: '+name);
		var d = when.defer();
		var configFile = getScriptedRcFileLocation(name);
		debug_log('scriptedrc file path = '+configFile);
		if (configFile) {
			parseJsonFile(configFile, function (jsonData) {
				d.resolve(jsonData);
			});
		} else {
			d.resolve({});
		}
		return d;
	}

	function convertRcFileToDir(loc) {
		return getContents(loc).then(function (contents) {
			debug_log('got contents of ' + loc );
			debug_log(contents);
			return pipeline([
				function () {
					debug_log('Deleting ...');
					return deleteResource(loc).then(function () {
						debug_log('Deleting OK');
					});
				},
				function () {
					debug_log('Mkdir '+loc+' ...');
					return mkdir(loc).then(function () {
						debug_log('Mkdir OK');
					});
				},
				function () {
					var putLoc = pathResolve(loc, MAIN_SCRIPTED_RC_FILE);
					debug_log('putting contents to '+putLoc+' ...');
					return putContents(putLoc, contents).then(function () {
						debug_log('putting OK');
					});
				}
			]);
		});
	}

	/**
	 * Ensures that .scriptedrc is in directory format. If it isn't yet...
	 * then migrate it.
	 */
	function ensureDirectoryForm() {
		debug_log('ensure directory form');
		var loc = getScriptedRcDirLocation();
		return stat(loc).then(
			function (s) {
				if (s.isDirectory) {
					debug_log('Already a dir => DONE');
					//okay!
				} else if (s.isFile) {
					debug_log('It is a file');
					return convertRcFileToDir(loc);
				}
			},
			function (err) {
				//probably means file/dir doesn't exist. So create it.
				return mkdir(loc);
			}
		);
	}

	function putScriptedRcFile(name, contents) {
		return when(ensureDirectoryForm(), function () {
			debug_log('putScriptedRcFile: '+ name);
			debug_log(JSON.stringify(contents, null, '  '));
			var loc = getScriptedRcFileLocation(name);
			return putContents(loc, JSON.stringify(contents, null, '  '));
		});
	}

	return {
		getConfiguration: getConfiguration,
		getScriptedRcFile: getScriptedRcFile,
		putScriptedRcFile: putScriptedRcFile
	};

}

exports.configure = configure;
<|endoftext|>