var Sequelize = require('sequelize'),
  path = require('path'),
  fs = require('fs')

var assert = require('assert'),
  debug = require('debug')('bshed:models')

/**
 * Model loader
 *
 * requires opts.config
 * returns models object
 */
module.exports = function modelsLoader ({config}={}) {
  assert(config)
  debug('loader:start')

  var models = {},
    sequelize = new Sequelize(config.database, config.username, config.password, config)

  // Load models
  fs.readdirSync(__dirname)
  .filter(file => file.indexOf('.') !== 0 && file !== 'index.js' && file !== 'test')
  .forEach(file => {
    var modelPath = path.join(__dirname, file)
    var model = sequelize.import(modelPath)
    models[model.name] = model
    debug(`${model.name} loaded from file ${modelPath}`)
  })

  // Associate and initialize models
  Object.keys(models).forEach(name => {
    ['associate', 'initialize'].forEach(action => {
      if (action in models[name]) {
        debug(`${action} ${name}`)
        models[name][action](models)
      }
    })
  })

  models.sequelize = sequelize
  models.Sequelize = Sequelize

  debug('loader:end')
  return models
}

@@ -1,21 +1,17 @@
 var 
-Sequelize
+debug
  = requi
@@ -18,51 +18,45 @@
 re('
-sequelize'),%0A  path = require('path'),%0A  fs
+debug')('bshed:models')%0Avar Sequelize
  = r
@@ -67,14 +67,20 @@
 re('
-f
 s
+equelize
 ')%0A
-%0A
 var 
@@ -109,17 +109,17 @@
 rt')
-,%0A  debug
+%0Avar path
  = r
@@ -126,36 +126,42 @@
 equire('
-debug')('bshed:model
+path')%0Avar fs = require('f
 s')%0A%0A/**
@@ -183,20 +183,48 @@
 r%0A *
-%0A * requires
+ @param %7BObject%7D opts%0A * @param %7BObject%7D
  opt
@@ -239,16 +239,17 @@
 %0A * 
+@
 returns 
 mode
@@ -248,21 +248,23 @@
 rns 
-models object
+%7BObject%7D Models
 %0A */
@@ -334,16 +334,48 @@
 t(config
+, 'model loader requires config'
 )%0A  debu
@@ -414,13 +414,14 @@
 = %7B%7D
-,
 %0A  
- 
+var
  seq
@@ -443,16 +443,21 @@
 quelize(
+%0A    
 config.d
@@ -464,16 +464,20 @@
 atabase,
+%0A   
  config.
@@ -485,16 +485,20 @@
 sername,
+%0A   
  config.
@@ -506,23 +506,30 @@
 assword,
+%0A   
  config
+%0A  
 )%0A%0A  // 
@@ -570,16 +570,18 @@
 name)%0A  
+ 
+ 
 .filter(
@@ -587,16 +587,22 @@
 (file =%3E
+%0A     
  file.in
@@ -659,18 +659,25 @@
 = 'test'
-)
 %0A
+    )%0A  
   .forEa
@@ -685,24 +685,26 @@
 h(file =%3E %7B%0A
+  
     var mode
@@ -738,24 +738,26 @@
 , file)%0A    
+  
 var model = 
@@ -784,16 +784,18 @@
 elPath)%0A
+  
     mode
@@ -817,24 +817,26 @@
 = model%0A    
+  
 debug(%60$%7Bmod
@@ -876,16 +876,18 @@
 Path%7D%60)%0A
+  
   %7D)%0A%0A  

Update model loader