{Model, ObjectId, mongodb} = require '../lib'
{Db, Server} = mongodb
{log} = console

Model.setClient 'mongodb://localhost:27017/bongo_test'

class Foo extends Model
  
  @set
    
#    client      : # credentials
#      server    :   'localhost'
#      port      :   27017
#      database  :   'test'
    
    schema        : # annotations:
      test1       :
        type      :   Number
        validator :   ['not enough', (value)-> value > 10]
        set       :   (value)-> Math.ceil 10 + value * 25
      test2       :
        type      :   Number
        validator :   ['range error', (value)-> 15 < value < 30]
      test3       :
        type      :   String
        pattern   :   /[a-z]+/
      test4       :   Object
      test5       : 
        type      :   Date
        default   :   -> new Date
      test6       :   ObjectId
      test7       :   [String]
      test8       :   [Foo]

class Bar extends Model
  @setSchema
    best1       : String
    best2       : Foo
    # this is a normal embedded schema.  nothing fancy.
    # it works because Foo is a *constructor, not an instance.'

class SaveRecord extends Model
  @setSchema
    createdAt       : 
      type          : Date
      default       : -> new Date
    collectionName  : String

foo = new Foo
  test1     : Math.random()
  test2     : Math.floor 15 + Math.random() * 15
  test3     : 'sldkajsldja'
  test4     :
    isAdHoc : yes

foo.on 'save', (step)->
  switch step
    when 1        then log 'saving a root document.'
    when Math.PI  then log 'saving a nested document.'

bar = new Bar
  best1: 'cowabunga, dude'
  best2: foo

bar.on 'error', (err)->

foo.save()

setInterval ->
  model = if Math.random() > .5 then bar else foo
  collectionName = model.getCollectionName()
  log collectionName
  saveRecord = new SaveRecord {collectionName}
  saveRecord.save()
  model.save()
, 1000

##foo.validate (errs)->
##  if errs.length is 1
##    throw errs[0]
##  else if errs.length
##    throw new Error 'There were some problems with your input.'
#
## nested schemas:
##
#class Bar extends Model
#  @setSchema
#    best1       : String
#    best2       : Foo
#    # this is a normal embedded schema.  nothing fancy.
#    # it works because Foo is a *constructor, not an instance.'
#
##bar = new Bar
##  best1: 'cowabunga, dude'
##  best2: foo
##  
#bar2 = new Bar
#  best1     : 'second test'
#  best2     : 
#    test1   : 6
#    test2   : 18
#    test8   : 
#      [
#        {
#          test1 : 4
#          test2 : 16
#        }
#        {
#          test1 : 13
#          test2 : 25
#        }
#      ]
#    
#class Baz extends Model
#  @setSchema
#    boast1: String
#    boast2: Bar
#
#baz = new Baz
#  boast1: 'arbitrary depth'
#  boast2: bar2
#
#bar2.save console.log
#
#    