 
   eventSourceable: null
   initializingMessage: null
+  routeCommands: null
   routeEvents: null
-  routeCommands: null
   eventCorrelationProperty: null
 
   constructor: ->

    if @routeEvents.length > 0 and not @eventCorrelationProperty?
      throw new Error Router.ERRORS.missingEventCorrelationProperty
    @routeCommands ?= []
    super

  onDependenciesReady: ->
    super
    @_setupInitializingMessage()
    @_routeEventToEventSourceable(eventType) for eventType in @routeEvents
    @_routeCommandToEventSourceable(commandType) for commandType in @routeCommands

  _setupInitializingMessage: ->
    if @initializingMessage.isSubclassOf(Space.messaging.Event)
      @eventBus.subscribeTo @initializingMessage, (event) =>
        @log.info("#{this}: Creating new #{@eventSourceable} with event
                  #{event.typeName()}\n", event)
        eventSourceable = @_handleDomainErrors(-> new @eventSourceable event)
        @repository.save(eventSourceable) if eventSourceable?
    else if @initializingMessage.isSubclassOf(Space.messaging.Command)
      @commandBus.registerHandler @initializingMessage, (cmd) =>
        @log.info("#{this}: Creating new #{@eventSourceable} with command
                  #{cmd.typeName()}\n", cmd)
        eventSourceable = @_handleDomainErrors(-> new @eventSourceable cmd)
        @repository.save(eventSourceable) if eventSourceable?

  _routeEventToEventSourceable: (eventType) ->
    @eventBus.subscribeTo eventType, @_genericEventHandler

class Space.eventSourcing.Router extends Space.Object
  @type 'Space.eventSourcing.Router'

  @mixin [
    Space.messaging.CommandHandling
    Space.messaging.EventSubscribing
    Space.messaging.EventPublishing
  ]

  _commandHandlers: {}

  dependencies: {
    repository: 'Space.eventSourcing.Repository'
    injector: 'Injector'
    configuration: 'configuration'
    commandBus: 'Space.messaging.CommandBus'
    eventBus: 'Space.messaging.EventBus'
    log: 'log'
  }

  ERRORS: {
    managedEventSourcableNotSpecified: 'Please specify a Router::eventSourceable
    class to be managed by the router.'

    missingInitializingMessage: 'Please specify Router::initializingMessage
    (an event or command class) that will be used to create new instances of
    the managed eventSourceable.'

    missingEventCorrelationProperty: 'Please specify Process::eventCorrelationProperty
