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

VideoActions = @VideoActions

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

@VideoStore = Reflux.createStore(
  {
    listenables: VideoActions
    logger: context.JK.logger
    videoShared: false
    videoOpen : false
    state : null
    everDisabled : false

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

    onAppInit: (@app) ->



        # someone has requested us to refresh our config
    onRefresh: ->

      # don't do any check if this is a client with no video enabled
      return unless context.jamClient.FTUECurrentSelectedVideoDevice?

      videoEnabled = context.jamClient.FTUEGetVideoShareEnable()

      @videoEnabled = videoEnabled

      if videoEnabled
        currentDevice = context.jamClient.FTUECurrentSelectedVideoDevice()
        deviceNames = context.jamClient.FTUEGetVideoCaptureDeviceNames()
        #deviceCaps = context.jamClient.FTUEGetVideoCaptureDeviceCapabilities()
        captureResolutions = context.jamClient.FTUEGetCaptureResolution()
        currentCaptureResolution = context.jamClient.FTUEGetCurrentCaptureResolution()

        logger.debug("captureResolutions, currentCaptureResolution", captureResolutions, currentCaptureResolution)
      else
        @everDisabled = true
        # don't talk to the backend when video is disabled; avoiding crashes
        currentDevice = null
        deviceNames = {}
        captureResolutions: {}
        currentCaptureResolution: null
        frameRates: {}


    #deviceCaps: deviceCaps,

      @state = {
        currentDevice: currentDevice,
        deviceNames: deviceNames,
        captureResolutions: captureResolutions,
        currentCaptureResolution: currentCaptureResolution,
        videoShared: @videoShared
        videoOpen: @videoOpen,
        videoEnabled: videoEnabled,
        everDisabled: @everDisabled
      }
      this.trigger(@state)

    onSetVideoEnabled: (enable) ->

      return unless context.jamClient.FTUESetVideoShareEnable?

      context.jamClient.FTUESetVideoShareEnable(enable)

      # keep state in sync
      @state.videoEnabled = enable
      @onRefresh()

    onStartVideo: ->
      return unless context.jamClient.SessStartVideoSharing?

      if @howtoWindow?
        @howtoWindow.close()
        @howtoWindow = null
      #else # TESTING
      #  @howtoWindow = window.open("/popups/how-to-use-video", 'How to Use Video', 'scrollbars=yes,toolbar=no,status=no,height=315,width=320')

      @logger.debug("SessStartVideoSharing()")
      context.jamClient.SessStartVideoSharing(0)
      @videoShared = true

      @state.videoShared = @videoShared
      this.trigger(@state)

    onStopVideo: ->
      if @videoShared
        @logger.debug("SessStopVideoSharing()")
        context.jamClient.SessStopVideoSharing()
        @videoShared = false
        @state.videoShared = @videoShared
        this.trigger(@state)

    onBringVideoToFront: ->
      if @videoShared
        @logger.debug("BringVideoToFront")
        context.jamClient.BringVideoWindowToFront();

    onTestVideo: () ->

      return unless context.jamClient.testVideoRender?
      result = context.jamClient.testVideoRender()

      if !result
        @app.layout.notify({title: 'Unable to initialize video window', text: "Please contact support@jamkazam.com"})

    onToggleVideo: () ->
      if @videoShared
        @onBringVideoToFront()
      else
        @onStartVideo()

    onSetCaptureResolution: (resolution) ->
      @logger.debug("set capture resolution: #{resolution}")
      context.jamClient.FTUESetCaptureResolution(resolution)
      @state.currentCaptureResolution = resolution
      this.trigger(@state)

    onSetSendFrameRate: (frameRates) ->
      @logger.debug("set capture frame rate: #{frameRates}")
      context.jamClient.FTUESetSendFrameRates(frameRates)
      @state.currentFrameRate = frameRates
      this.trigger(@state)

    onRefreshVideoState:()->
      @logger.debug("onRefreshVideoState")
      openVideoSources = context.jamClient.getOpenVideoSources()
      @logger.debug("onRefreshVideoState", openVideoSources)

      # possible keys, all bool values
      #"session_window", "webcam1", "webcam2", "screen_capture"

      # ex: with mac webcam open only: session_window: 2, webcam1: 1}
      # no webcam open: Object {}

      @openVideoSources = openVideoSources
      @anyVideoOpen = Object.keys(openVideoSources).length > 0
      @state.anyVideoOpen = Object.keys(openVideoSources).length > 0
      this.trigger(@state)

    onSelectDevice: (device, caps) ->

      # don't do anything if no video capabilities
      return unless context.jamClient.FTUESelectVideoCaptureDevice?

      result = context.jamClient.FTUESelectVideoCaptureDevice(device, caps)
      if(!result)
        @logger.error("onSelectDevice failed with device #{device}")
        @app.layout.notify({title: 'Unable to select webcam', text: "Please try reconnecting webcam."})
      else
        @state.currentDevice = context.jamClient.FTUECurrentSelectedVideoDevice();
        this.trigger(@state)

    onVideoWindowOpened: () ->
      @onRefresh() unless @state?

      @logger.debug("in session? #{context.SessionStore.inSession()}, currentDevice? #{@state?.currentDevice?}, videoShared? #{@videoShared}")

      if context.SessionStore.inSession() && @state.currentDevice? && Object.keys(@state.currentDevice).length > 0 && !@videoShared
        context.JK.ModUtils.shouldShow(NAMED_MESSAGES.HOWTO_USE_VIDEO_NOSHOW).done((shouldShow) =>
          @logger.debug("checking if user has 'should show' on video howto: #{shouldShow}")
          if shouldShow
            @howtoWindow = window.open("/popups/how-to-use-video", 'How to Use Video', 'scrollbars=yes,toolbar=no,status=no,height=315,width=320')
        )

      #@howtoWindo.ParentRecordingStore = context.RecordingStore
      #@howtoWindo.ParentIsRecording = @recordingModel.isRecording()

      @videoOpen = true
      @state.videoOpen = @videoOpen
      this.trigger(@state)

    onVideoWindowClosed: () ->
      @onRefresh() unless @state?

      if @howtoWindow?
        @howtoWindow.close()
        @howtoWindow = null

      @videoOpen = false
      @state.videoOpen = @videoOpen
      @videoShared = false
      @state.videoShared = @videoShared
      this.trigger(@state)

    onHowToUseVideoPopupClosed: (dontShow) ->
      if (dontShow)
        @logger.debug("requesting that user no longer see how-to-use-video")
        context.JK.ModUtils.updateNoShow(NAMED_MESSAGES.HOWTO_USE_VIDEO_NOSHOW);

      logger.debug("how-to-use-video popup closed")
      @howtoWindow = null

    onConfigureVideoPopupClosed: (dontShow) ->
      if (dontShow)
        @logger.debug("requesting that user no longer see configure-video")
        context.JK.ModUtils.updateNoShow(NAMED_MESSAGES.CONFIGURE_VIDEO_NOSHOW);

      logger.debug("configure-video popup closed")
      @configureWindow = null

    # if the user passes all the safeguards, let's see if we should get them to configure video
    onCheckPromptConfigureVideo: () ->
      # don't do any check if this is a client with no video enabled
      return unless context.jamClient.FTUECurrentSelectedVideoDevice?

      @onRefresh() unless @state?

      @logger.debug("checkPromptConfigureVideo", @state.currentDevice, @state.deviceNames)

      # if no device configured and this is the native client and if you have at least 1 video
      # currentDevice, from the backend, is '{'':''}' in the case of no device configured.  But we also check for an empty object, or null object.
      if (!@state.currentDevice? || Object.keys(@state.currentDevice).length == 0 || (Object.keys(@state.currentDevice).length == 1 && @state.currentDevice[''] == '')) && gon?.isNativeClient && Object.keys(@state.deviceNames).length > 0
        # and if they haven't said stop bothering me about this
        context.JK.ModUtils.shouldShow(NAMED_MESSAGES.CONFIGURE_VIDEO_NOSHOW).done((shouldShow) =>
          @logger.debug("checking if user has 'should show' on video config: #{shouldShow}")
          if shouldShow
            @configureWindow = window.open("/popups/configure-video", 'Configure Video', 'scrollbars=yes,toolbar=no,status=no,height=395,width=444')
        )

    isVideoEnabled:() ->
      return @videoEnabled


  }
)
