$ = jQuery
context = window
logger = context.JK.logger
rest = context.JK.Rest()
EVENTS = context.JK.EVENTS


JamTrackActions = @JamTrackActions

@JamTrackMixdownStore = Reflux.createStore(
  {
   # listenables: JamTrackMixdownActions

    # the jamtrack that contains the mixdowns in question
    jamTrack: null

    # what mixdowns are being built right now
    building: []

    # a currently open (loaded) mixdown
    current: null

    init: () ->
      this.listenTo(context.AppStore, this.onAppInit);
      this.listenTo(context.JamTrackStore, this.onJamTrackChanged);

      @changed()

    onAppInit: (@app) ->

    getState: () ->
      @state

    changed: () ->
      @state = {jamTrack: @jamTrack, building:@building, current: @current}
      this.trigger(@state)

    onJamTrackChanged: (@jamTrack) ->
      # TODO: close out building? current?

    onCreateMixdown: (mixdown, package_settings, done, fail) ->
      logger.debug("creating mixdown", mixdown, package_settings)
      rest.createMixdown(mixdown)
      .done((created) =>

        logger.debug("created mixdown", created)

        package_settings.id = created.id

        # we have to determine sample rate here, in the store, because child windows don't have access to jamClient
        sampleRate = context.jamClient.GetSampleRate()
        sampleRate = if sampleRate == 48 then 48 else 44
        package_settings.sample_rate = sampleRate

        rest.enqueueMixdown(package_settings)
        .done((enqueued) =>
          logger.debug("enqueued mixdown package", package_settings)
          done(enqueued)
        )
        .fail((jqxhr) =>
          @app.layout.notify({title:'Unable to Package Mixdown', text: 'You can push the RETRY button.'})
          fail(jqxhr)
        )
      )
      .fail((jqxhr) =>
        fail(jqxhr)
      )

    onEditMixdown: (mixdown) ->
      logger.debug("editing mixdown", mixdown)

    onDeleteMixdown: (mixdown) ->
      logger.debug("deleting mixdown", mixdown)

    onOpenMixdown: (mixdown) ->
      logger.debug("opening mixdown", mixdown)

    onCloseMixdown: (mixdown) ->
      logger.debug("closing mixdown", mixdown)

    onEnqueueMixdown: (mixdown) ->
      logger.debug("enqueuing mixdown", mixdown)

    onDownloadMixdown: (mixdown) ->
      logger.debug("download mixdown", mixdown)

    onRefreshMixdown: (mixdown) ->
      logger.debug("refresh mixdown", mixdown)
  }
)