$ = jQuery
context = window
logger = context.JK.logger

BackendToFrontendFPS = {

  0: 30,
  1: 24,
  2: 20,
  3: 15,
  4: 10
}

@RecordingStore = Reflux.createStore(
  {
    listenables: @RecordingActions
    recordingWindow: null

    init: ->
      # Register with the app store to get @app
      this.listenTo(context.AppStore, this.onAppInit)

    onSessionEnded: () ->
      if @recordingWindow?
        @recordingWindow.close()

    onAppInit: (app) ->
      @app = app
      $(context.AppStore).on('SessionEnded', @onSessionEnded)

    onInitModel: (recordingModel) ->
      @recordingModel = recordingModel
      this.trigger({isRecording: @recordingModel.isRecording()})

    onStartRecording: (recordVideo, recordChat) ->
      frameRate = 0
      if recordVideo
        if context.jamClient.GetCurrentVideoFrameRate?
          frameRate = context.jamClient.GetCurrentVideoFrameRate() || 0;
          frameRate = BackendToFrontendFPS[frameRate]

      NoVideoRecordActive = 0
      WebCamRecordActive = 1
      ScreenRecordActive = 2
      logger.debug("onStartRecording: recordVideo: #{recordVideo}, recordChat: #{recordChat} frameRate: #{frameRate}")
      @recordingModel.startRecording(recordVideo, recordChat, frameRate)

    onStopRecording: () ->
      @recordingModel.stopRecording()

    onStartingRecording: (details) ->
      details.cause = 'starting'
      @mixTransferred = false
      this.trigger(details)

      @popupRecordingControls() unless @recordingWindow?

    onStartedRecording: (details) ->
      details.cause = 'started'
      @mixTransferred = false
      this.trigger(details)

      @popupRecordingControls() unless @recordingWindow?

    onStoppingRecording: (details) ->
      details.cause = 'stopping'

      this.trigger(details)

    onStoppedRecording: (details) ->
      details.cause = 'stopped'

      if @recordingWindow?
        @recordingWindow.close()

      this.trigger(details)

    onAbortedRecording: (details) ->
      details.cause = 'aborted'

      if @recordingWindow?
        @recordingWindow.close()

      this.trigger(details)

    onOpenRecordingControls: () ->
      logger.debug("recording controls opening")

      if @recordingWindow?
        @recordingWindow.close()

      @popupRecordingControls()

    onRecordingControlsClosed: () ->
      logger.debug("recording controls closed")
      @recordingWindow = null

    onMixTransferred: () ->
      @mixTransferred = true

    popupRecordingControls: () ->
      logger.debug("poupRecordingControls")
      @recordingWindow = window.open("/popups/recording-controls", 'Recording', 'scrollbars=yes,toolbar=no,status=no,height=315,width=340')
      @recordingWindow.ParentRecordingStore = context.RecordingStore
      @recordingWindow.ParentIsRecording = @recordingModel.isRecording()

  }
)
