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

NoVideoRecordActive = 0
WebCamRecordActive = 1
ScreenRecordActive = 2

mixins = []

# make sure this is actually us opening the window, not someone else (by checking for MixerStore)

# this check ensures we attempt to listen if this component is created in a popup
reactContext = if window.opener? then window.opener else window

accessOpener = false
if window.opener?
  try
    m = window.opener.MixerStore
    accessOpener = true
  catch e
    reactContext = window

VideoUploaderStore = reactContext.VideoUploaderStore
VideoUploaderActions = reactContext.VideoUploaderActions
AppActions = reactContext.AppActions

if accessOpener
  mixins.push(Reflux.listenTo(VideoUploaderStore,"onVideoUploadChanged"))

@PopupVideoUploader = React.createClass({
  mixins: mixins

  onVideoUploadChanged: (uploadState) ->
    this.setState({uploadState: uploadState})

  render: () ->

    # there are a few initial states: if auth is null, we don't know yet (and are checking against the server)
    # if auth is set, then we can show the upload btn
    # and if auth == false, then we need the user to try and log in


    if @state.recording

      name = @state.recording.my?.name
      description = @state.recording.my?.description
      created = @state.recording.created_at

      if @state.deleteMe
        action = `<div><a className="button-grey close-btn" onClick={this.onCloseRequested}>CANCEL</a> <a className="button-orange close-btn" onClick={this.onDeleteVideo}>DELETE</a></div>`
        instructions = `<p>Save space and delete your video from your computer?</p>`
      else if @state.recording.video_url?
        action = `<a className="button-orange close-btn" onClick={this.onCloseRequested}>CLOSE</a>`
        instructions = `<p>Your video has been uploaded previously.  <a className="video-url" onClick={this.watchVideo} href={this.state.recording.video_url}>{this.state.uploadState.videoUrl}</a></p>`
      else if @state.uploadState.errorReason
        action = `<a className="button-orange upload-btn" onClick={this.onUploadRequested}>UPLOAD</a>`
        instructions = `<p>The upload failed.  You can try again.  ({this.state.uploadState.errorReason})</p>`
      else if @state.uploadState.done
        action = `<a className="button-orange close-btn" onClick={this.onNextToDeletion}>OK</a>`
        instructions = `<p>Your video has been uploaded successfully. <a className="video-url" onClick={this.watchVideo} href={this.state.uploadState.videoUrl}>{this.state.uploadState.videoUrl}</a></p>`
      else if @state.uploadState.paused
        action = `<a className="button-orange resume-btn" onClick={this.onResumeRequested}>RESUME</a>`
        instructions = `<p>Press the RESUME button at any time to continue uploading your video.</p>`
      else if @state.uploadState.uploading
        action = `<div><a className="button-grey cancel-btn" onClick={this.onCancelRequested}>CANCEL</a> <a className="button-grey pause-btn" onClick={this.onPauseRequested}>PAUSE</a></div>`
        width = ((@state.uploadState.bytesSent / @state.uploadState.bytesTotal) * 100)
        progressWidth = width.toString() + "%";
        progressStyle = {width:progressWidth}
        rounded = Math.round(width)
        instructions = `<p>Press the PAUSE button at any time to pause the upload of your video, or CANCEL to end this upload completely.
        <div className="progress-bar" style={progressStyle}><div className="percentage-progress">{rounded}%</div></div>
        </p>`
      else if @state.auth == false
        action = `<input className="google_login_button" type='image' src="/assets/google_signin.png" height="30px" onClick={this.startGoogleLogin}/>`
        instructions = `<p>To upload this recording to YouTube, you must give JamKazam the necessary access to your YouTube account by clicking the button below.</p>`
      else if @state.auth?
        action = `<a className="button-orange upload-btn" onClick={this.onUploadRequested}>UPLOAD</a>`
        instructions = `<p>Press the UPLOAD button to start uploading your video to YouTube.  When the upload is done, a link to your video will appear.</p>`
      else
        name = null
        action = null
    else
      name = null
      action = null

    `<div className="video-uploader">
      <h3>Upload Video<br/>"{name}"</h3>
      <h3></h3>
      {instructions}
      <div className="control-holder">
        {action}
      </div>
    </div>`

  getInitialState: () ->
    {auth: null, uploadState: VideoUploaderStore.getState(), deleteMe: false}

  watchVideo: (e) ->
    e.preventDefault()
    $link = $(e.target)
    AppActions.openExternalUrl($link.attr('href'))

  onNextToDeletion: (e) ->
    e.preventDefault();
    @setState({deleteMe: true})

  onCloseRequested: (e) ->
    e.preventDefault()
    window.close()

  onDeleteVideo: (e) ->
    e.preventDefault();
    VideoUploaderActions.delete(gon.recording_id)
    window.close()

  startGoogleLogin: (e) ->
    e.preventDefault()

    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: () ->
    window._oauth_win.close()
    @checkAuth()

  onUploadRequested: (e) ->
    e.preventDefault()
    VideoUploaderActions.uploadVideo(gon.recording_id)

  onResumeRequested: (e) ->
    e.preventDefault()
    VideoUploaderActions.resume(gon.recording_id)

  onPauseRequested: (e) ->
    e.preventDefault()
    VideoUploaderActions.pause(gon.recording_id)

  onCancelRequested: (e) ->
    e.preventDefault()
    VideoUploaderActions.cancel(gon.recording_id)

  checkAuth:() ->
    rest.getGoogleAuth()
    .done((auth) =>
      if auth.auth?
        @setState({auth: auth.auth})
      else
        @setState({auth: false})
    )
    .fail(() =>
      @setState({errorReason: 'Unable to fetch user authorization'})
    )

  checkRecording:() ->
    rest.getRecording({id: gon.recording_id})
    .done((response) =>
      logger.debug("recording info fetched #{response}")
      @setState({recording:response})
    )
    .fail((jqXHR) =>
      logger.debug("recording info fetch failed #{jqXHR.responseText}")
      @setState({errorReason: 'Unable to fetch recording info'})
    )

  componentDidMount: () ->

    $(window).unload(@windowUnloaded)


    @checkAuth()
    @checkRecording()
    VideoUploaderActions.newVideo(gon.recording_id)

    @resizeWindow()

    # this is necessary due to whatever the client's rendering behavior is.
    setTimeout(@resizeWindow, 300)

  componentDidUpdate: () ->
    @resizeWindow()
    setTimeout(@resizeWindow, 1000)

  resizeWindow: () =>
    $container = $('#minimal-container')
    width = $container.width()
    height = $container.height()

    # there is 20px or so of unused space at the top of the page.   can't figure out why it's there. (above #minimal-container)
    #mysteryTopMargin = 20
    mysteryTopMargin = 0
    # deal with chrome in real browsers
    offset = (window.outerHeight - window.innerHeight) + mysteryTopMargin

    # handle native client chrome that the above outer-inner doesn't catch
    #if navigator.userAgent.indexOf('JamKazam') > -1

    #offset += 25

    width = 100 if width < 100
    height = 100 if height < 100

    window.resizeTo(width, height + offset)

  windowUnloaded: () ->
    VideoUploaderActions.uploaderClosed()
})