"use strict";

var fs        = require("fs");
var path      = require("path");
var Sequelize = require("sequelize");
var env       = "dev";
var config    = require(path.join(__dirname, '..', 'config', 'database.json'))[env];
// MySQL database:
var sequelize = new Sequelize(config.database, config.user , config.password , {
  host: config.host,
  port: config.port,
  dialect: config.driver,
  define: {
        timestamps: false,
  },
  pool: {
    max: 5,
    maxIdleTime: 30
    //min: 0,
    //idle: 10000
  },
  logging: false
});

var db        = {};

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf(".") !== 0) && (file !== "index.js");
  })
  .forEach(function(file) {
    var model = sequelize.import(path.join(__dirname, file));
    db[model.name] = model;
  });

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

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
