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

VideoLiveStreamActions = @VideoLiveStreamActions

@VideoLiveStreamStore = Reflux.createStore(
  {
    listenables: VideoLiveStreamActions
    logger: context.JK.logger
    creatingBroadcast: false

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

    onAppInit: (@app) ->

    onPopupClosed: () ->

      if @childWindow?
        @childWindow = null

      logger.debug("Popup closed")
      context.jamClient.StopLiveStreaming()
      @streaming = false
      @onRefresh()


    onRefresh: () ->
      @state = {
        creatingBroadcast: @creatingBroadcast,
        createdStream: @createdStream,
        createStreamError: @createStreamError,
        waitingForReady: @waitingForReady,
        waitingOnTesting: @waitingOnTesting,
        waitingOnActiveStream: @waitingOnActiveStream,
        waitingOnLive: @waitingOnLive,
        transitioningTesting: @transitioningTesting,
        streaming: @streaming,
        errorMessage: @errorMessage,
        broadcast: @broadcast
      }
      this.trigger(@state)

    onStartLiveStream: () ->
      @creatingBroadcast = false
      @createdStream = false
      @createStreamError = false
      @transitioningTesting = false
      @waitingForReady = false
      @waitingOnLive = false
      @waitingOnTesting = false
      @waitingOnActiveStream = false
      @errorMessage = null
      @streaming = false

      @logger.debug("onStartLiveStream")
      @onRefresh()

      if @childWindow?
        logger.debug("show live stream popup being closed automatically")
        @childWindow.close()
        @childWindow = null

      @childWindow = window.open("/popups/video/stream/" + context.SessionStore.id(), 'Video Live Stream', 'scrollbars=yes,toolbar=no,status=no,height=155,width=350')

    startLiveStreaming: () ->
      @logger.debug("user requests live stream")
      @createLiveStream()

    # do not use; here until can remove
    startGoogleLogin: (e) ->

      @logger.debug("Starting google login")
      window._oauth_win = window.open("/auth/google_login", "Log In to Google", "height=700,width=500,menubar=no,resizable=no,status=no");
      window._oauth_callback = @oauthCallback

    oauthCallback: () ->
      @creatingBroadcast = true
      @logger.debug("oauthCallback... checking auth")
      window._oauth_win.close()
      @checkAuth()

    checkAuth:() ->
      rest.getGoogleAuth()
      .done((auth) =>
        @logger.debug("check Auth is done", auth)
        if auth.auth?
          @createLiveStream()
        else
          @creatingBroadcast = false
          @onRefresh()
        # alert to user
      )
      .fail(() =>
        @creatingBroadcast = false
        @onRefresh()
        # lert to user
      )

    loadBroadcast: (sessionId) ->
      @broadcast = null
      @onRefresh()
      @fetchBroadcast(sessionId)

    fetchBroadcast: (sessionId) ->
      rest.getLiveStream(sessionId)
      .done((broadcast) =>
        @broadcast = broadcast
        @onRefresh()
      )
      .fail((jqXHR) =>
        logger.error("unable to fetch broadcast", jqXHR.responseText)
        @onRefresh()
      )

    createLiveStream: () ->

      @creatingBroadcast = true

      rest.createLiveStream(context.SessionStore.id())
      .done((broadcast) =>
        @creatingBroadcast = false
        @broadcast = broadcast
        @onRefresh()
        success = context.jamClient.StartLiveStreaming(broadcast.stream_name)

        if success
          @createdStream = true
          @waitingForReady = true
          @transitionTimeout = new Date().getTime() + 60000 # die in 10 seconds
          @onRefresh()
          setTimeout(() =>
            @waitForReady()
          , 1000)

        else
          @createStreamError = true
          @onRefresh()
      )
      .fail(() =>
        @creatingBroadcast = false
        @onRefresh()
      )

    waitForReady: () ->
      rest.getLiveStream(context.SessionStore.id())
      .done((broadcast) =>
        @broadcast = broadcast
        if broadcast.broadcast_status == 'ready' || broadcast.broadcast_status == 'live'
          @waitingForReady = false
          @transitionTimeout = new Date().getTime() + 60000 # die in 20 seconds
          @waitForActiveStream()
        else
          if new Date().getTime() > @transitionTimeout
            # uh oh.  waited fo ra while; broadcast never becam ready
            @errorMessage = 'YouTube never indicated broadcast is ready'
            @waitingForReady = false
            @onRefresh()
          else
            setTimeout(() =>
              @waitForReady()
            , 1000)
      )
      .fail(() =>
        @waitingForReady = false
        @errorMessage = 'Could not check status of YouTube broadcast'
        context.jamClient.StopLiveStreaming()
        @streaming = false
        @onRefresh()
      )

    transitionTesting: () ->
      @transitioningTesting = true
      @onRefresh()

      rest.liveStreamTransition(context.SessionStore.id(), 'testing')
      .done((broadcast) =>
        @broadcast = broadcast
        @transitioningTesting = false
        @waitingOnTesting = true
        @transitionTimeout = new Date().getTime() + 60000 # die in 20 seconds
        setTimeout(() =>
          @waitForTesting()
        , 1000)
      )
      .fail(() =>
        @transitioningTesting = false
        @errorMessage = 'Could not transition live stream to "testing"'
        context.jamClient.StopLiveStreaming()
        @streaming = false
        @onRefresh()
      )

    transitionLive: () ->
      @transitioningLive = true
      @onRefresh()

      rest.liveStreamTransition(context.SessionStore.id(), 'live')
      .done((broadcast) =>
        @broadcast = broadcast
        @transitioningLive = false
        @waitingOnLive = true
        @transitionTimeout = new Date().getTime() + 60000 # die in 20 seconds
        setTimeout(() =>
          @waitForLive()
        , 1000)
      )
      .fail(() =>
        @transitioningLive = false
        @errorMessage = 'Could not transition live stream to "live"'
        context.jamClient.StopLiveStreaming()
        @streaming = false
        @onRefresh()
      )


    waitForActiveStream: () ->
      rest.getLiveStream(context.SessionStore.id())
      .done((broadcast) =>
        @broadcast = broadcast
        if broadcast.stream_status == 'active'
          @waitingOnActiveStream = false
          @transitionTimeout = new Date().getTime() + 60000 # die in 20 seconds
          @transitionTesting()
        else
          if new Date().getTime() > @transitionTimeout
            # uh oh.  waited fo ra while; stream never became ready
            @errorMessage = 'YouTube never indicated stream came from the JamKazam application'
            @waitingOnActiveStream = false
            @onRefresh()
          else
            setTimeout(() =>
              @waitForActiveStream()
            , 1000)
      )
      .fail(() =>
        @waitingOnActiveStream = false
        @errorMessage = 'Could not check status of YouTube broadcast'
        context.jamClient.StopLiveStreaming()
        @streaming = false
        @onRefresh()
      )

    waitForTesting: () ->
      rest.getLiveStream(context.SessionStore.id())
      .done((broadcast) =>
        @broadcast = broadcast
        if broadcast.broadcast_status == 'testing' || broadcast.broadcast_status == 'live'
          @waitingOnTesting = false
          @transitionTimeout = new Date().getTime() + 60000 # die in 20 seconds
          @transitionLive()
        else
          if new Date().getTime() > @transitionTimeout
            # uh oh.  waited fo ra while; stream never became ready
            @errorMessage = 'YouTube never indicated stream converted to testing'
            @waitingOnTesting = false
            @onRefresh()
          else
            setTimeout(() =>
              @waitForTesting()
            , 1000)
      )
      .fail(() =>
        @waitingForTesting = false
        @errorMessage = 'Could not check status of YouTube broadcast'
        context.jamClient.StopLiveStreaming()
        @streaming = false
        @onRefresh()
      )

    waitForLive: () ->
      rest.getLiveStream(context.SessionStore.id())
      .done((broadcast) =>
        if broadcast.broadcast_status == 'live'
          @waitingOnLive = false
          @streaming = true
          console.log("BROADCAST TIME", broadcast)
          @onRefresh()
        else
          if new Date().getTime() > @transitionTimeout
            # uh oh.  waited fo ra while; stream never became ready
            @errorMessage = 'YouTube never indicated stream converted to live'
            @waitingOnLive = false
            @onRefresh()
          else
            setTimeout(() =>
              @waitForLive()
            , 1000)
      )
      .fail(() =>
        @waitingForLive = false
        @errorMessage = 'Could not check status of YouTube broadcast'
        context.jamClient.StopLiveStreaming()
        @streaming = false
        @onRefresh()
      )
  }
)