$ = jQuery
context = window
logger = context.JK.logger
PLAYBACK_MONITOR_MODE = context.JK.PLAYBACK_MONITOR_MODE
RecordingActions = @RecordingActions
BrowserMediaActions = @BrowserMediaActions

@BrowserMediaPlaybackStore = Reflux.createStore(
  {
    listenables: @BrowserMediaPlaybackActions

    playbackStateChanged: false
    positionUpdateChanged: false
    currentTimeChanged: false
    playbackState: null
    positionMs: 0
    durationMs: 0
    isRecording: false
    sessionHelper: null

    init: () ->
      this.listenTo(context.BrowserMediaStore, this.onBrowserMediaChange);

    onBrowserMediaChange: (changes) ->
      @onPositionUpdate(PLAYBACK_MONITOR_MODE.BROWSER_MEDIA)

    onCurrentTimeChanged: (time) ->
      @time = time
      @currentTimeChanged = true
      @issueChange()

    onMediaStartPlay: (data) ->
      BrowserMediaActions.play.trigger()

    onMediaStopPlay: (data) ->

      if !data.endReached
        BrowserMediaActions.stop()

    onMediaPausePlay: (data) ->
      # if a JamTrack is open, and the user hits 'pause' or 'stop', we need to automatically stop the recording
      if !data.endReached
        BrowserMediaActions.pause()

    onMediaChangePosition: (data) ->
      seek = data.positionMs;

      BrowserMediaActions.seek(seek);

    issueChange: () ->

      @state =
        playbackState: @playbackState
        playbackStateChanged: @playbackStateChanged
        positionUpdateChanged: @positionUpdateChanged
        currentTimeChanged: @currentTimeChanged
        positionMs: @positionMs
        durationMs: @durationMs
        isPlaying: @isPlaying
        time: @time

      this.trigger(@state)
      @playbackStateChanged = false
      @positionUpdateChanged = false
      @currentTimeChanged = false

    onPlaybackStateChange: (text) ->
      @playbackState = text
      @playbackStateChanged = true

      @issueChange()

    onPositionUpdate: (playbackMode) ->
      if playbackMode == PLAYBACK_MONITOR_MODE.BROWSER_MEDIA
        @positionMs = BrowserMediaStore.onGetPlayPosition() || 0
        @durationMs = BrowserMediaStore.onGetPlayDuration() || 0;
        @isPlaying = BrowserMediaStore.playing;
      else
        raise 'Only BROWSER_MEDIA is supported'
      @positionUpdateChanged = true
      @issueChange()

  }
)
