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 db = {};

const sequelize = new Sequelize(
    config.database.database,
    config.database.username,
    config.database.password,
    config.database, {
        dialect: 'mysql',
        operatorAliases: false,
        logging: config.debug,
        define: {
            charset: 'utf8',
            collate: 'utf8_general_ci',
        },        
        pool: {
            max: 140,
            min: 0,
            idle: 10000
        }
    }
);

try {
    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);
        }
    });
} catch (error) {
    console.error(error);
}

module.exports = db;