/*
 Copyright 2016 Covistra Technologies Inc.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

var serviceHandler = require('./service-handler');

module.exports = function(options) {
    options = options || {};

    return function(config, DBS, log, _, Promise, seneca, Schema) {
        var _resolveDB = Promise.method(function(name) {
            if(DBS) {
                return DBS.getDB(name);
            }
        });

        const Handlers = {
            create: require('./handlers/model-create-service'),
            update: require('./handlers/model-update-service'),
            load: require('./handlers/model-load-service'),
            list: require('./handlers/model-list-service'),
            remove: require('./handlers/model-remove-service')
        };

        return function(key, schema, hooks, opts = {}) {
            var dbPromise = _resolveDB(opts.db || config.db.default_db), model;

            if(options.testMode) {
                const MockedModel = require('./data-model/mocked-model');
                model = new MockedModel(key, schema, dbPromise, hooks);
            }
            else {
                const Model = require('./data-model/model');
                model = new Model(key, schema, dbPromise, hooks);
            }

            // Register handlers for all basic operations
            var createSpec = Handlers.create(model, Schema);
            var updateSpec = Handlers.update(model, Schema);
            var listSpec = Handlers.list(model, Schema);
            var loadSpec = Handlers.load(model, Schema);
            var removeSpec = Handlers.remove(model, Schema);

            seneca.add(createSpec.pattern, serviceHandler(createSpec, log));
            seneca.add(updateSpec.pattern, serviceHandler(updateSpec, log));
            seneca.add(listSpec.pattern, serviceHandler(listSpec, log));
            seneca.add(loadSpec.pattern, serviceHandler(loadSpec, log));
            seneca.add(removeSpec.pattern, serviceHandler(removeSpec, log));

            return model;
        }
    };
};
