const glob = require('glob');
const path = require('path');
const Sequelize = require('sequelize');

const config = require('../config');
const log = require('./logger');

const modulesDir = path.resolve(__dirname + '/../modules/')
const globOptions = {
    cwd: modulesDir,
    nocase: true,
    nodir: true,
    absolute: true,
}

log.info('Configurando DB.');

const sequelize = new Sequelize(
    config.database.database,
    config.database.username,
    config.database.password,
    config.database, {
        dialect: 'mysql',
        operatorAliases: false,
        logging: false,
    }
);

const db = {};
db.sequelize = sequelize;
db.Sequelize = Sequelize;

glob.sync("**/*.model.js", globOptions)
    .forEach(function (file) {
        var model = sequelize.import(file);
        log.info('Loading "' + model.name + '" model.');
        db[model.name] = model;
    });

Object.keys(db).forEach(function (modelName) {
    if (db[modelName].associate) {
        db[modelName].associate(db);
    }
});

module.exports = db;