context = window
logger = context.JK.logger
ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
rest = context.JK.Rest()

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
# make sure this is actually us opening the window, not someone else (by checking for MixerStore)
if window.opener?
  try
    m = window.opener.MixerStore
  catch e
    reactContext = window

# temporarily..
# reactContext = window

AppActions = reactContext.AppActions
JamTrackPlayerActions = reactContext.JamTrackPlayerActions
JamTrackPlayerStore = reactContext.JamTrackPlayerStore


@PopupJamTrackMixdownDownload = React.createClass({

  checkServerTimeout: null
  checkTime: 5000
  sampleRate: 48

  render: () ->
    if @state.mixdown?
      header = `<h2>Mix: "{this.state.mixdown.name}"</h2>`

      if @state.package?
        switch this.state.package.signing_state
          when 'QUIET_TIMEOUT'
            action = `<span className="action">Failure.  Try again? <button className="button-orange" onClick={this.enqueue}></button></span>`
          when 'QUIET'
            action = `<span className="action">Failure.  Try again? <button className="button-orange" onClick={this.enqueue}></button></span>`
          when 'QUEUED'
            action = `<span className="action">Creating mix... <img src="/assets/shared/spinner.gif" className="please-wait"/></span>`
          when 'QUEUED_TIMEOUT'
            action = `<span className="action">Failure.  Try again? <button className="button-orange" onClick={this.enqueue}></button></span>`
          when 'SIGNING'
            action = `<span className="action">Creating mix... <img src="/assets/shared/spinner.gif" className="please-wait"/></span>`
          when 'SIGNING_TIMEOUT'
            action = `<span className="action">Failure.  Try again? <button className="button-orange" onClick={this.enqueue}></button></span>`
          when 'SIGNED'
            action = `<span className="action"><button className="button-orange" onClick={this.download}>DOWNLOAD IN BROWSER</button></span>`
          when 'ERROR'
            action = `<span className="action">Failure.  Try again? <button className="button-orange" onClick={this.enqueue}></button></span>`
      else
        action = `<span className="action"><button className="button-orange enqueue" onClick={this.enqueue}>CREATE MP3</button></span>`

    else
      action = null

    `<div className="jamtrack-downloader">
      <div className="help-text">To download this mix or track, we first need to convert it to an MP3 file.</div>
      {header}
      {action}
    </div>`

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

    new window.Fingerprint2().get((result, components) => (
      redirectTo = "/api/mixdowns/#{@state.mixdown.id}/download.mp3?file_type=mp3&sample_rate=#{@sampleRate}&download=1&mark=#{result}"
      redirectTo = encodeURIComponent(redirectTo)
      AppActions.openExternalUrl(window.location.protocol + '//' + window.location.host + "/signin?redirect-to=#{redirectTo}")
    ))

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

    logger.debug("enqueuing mixdown")

    package_settings = {file_type: 'mp3', encrypt_type: null, sample_rate: @sampleRate}
    package_settings.id = @state.mixdown.id

    rest.enqueueMixdown(package_settings)
    .done((enqueued) =>
      @setState({package: enqueued})
    )
    .fail((jqxhr) =>
      @app.layout.notify({title:'Unable to Create Custom Mix', text: 'Click the error icon to retry.'})
      fail(jqxhr) if fail?
    )

  getInitialState: () ->
    {mixdown:null, package:null}

  getDefaultProps: () ->
    {fileType: 'mp3'}

  componentWillUpdate: (nextProps, nextState) ->

    cancelTimer = false
    setTimer = false
    if nextState.package?
      switch nextState.package.signing_state
        when 'QUIET_TIMEOUT'
          cancelTimer = true
        when 'QUIET'
          cancelTimer = true
        when 'QUEUED'
          setTimer = true
        when 'QUEUED_TIMEOUT'
          cancelTimer = true
        when 'SIGNING'
          setTimer = true
        when 'SIGNING_TIMEOUT'
          cancelTimer = true
        when 'SIGNED'
          cancelTimer = true
        when 'ERROR'
          cancelTimer = true
    else
      cancelTimer = true

    if cancelTimer && @checkServerTimer?
      logger.debug("canceling timer")
      clearTimeout(@checkServerTimer)
      @checkServerTimer = null

    if setTimer
      logger.debug("starting timer")
      if @checkServerTimer?
        clearTimeout(@checkServerTimer)
        @checkServerTimer = null

      @checkServerTimer = setTimeout((() =>
         @fetchJamTrackPackageInfo()
      ), @checkTime)

  componentDidMount: () ->

    @fetchJamTrackInfo()

  fetchJamTrackPackageInfo: () ->
    rest.getMixdownPackage({id: @state.package.id})
    .done((response) =>
      @setState({package: response})
    )
    .fail((jqXHR) =>
      alert("Unable to fetch JamTrack information. Try logging in.")
    )


  fetchJamTrackInfo: () ->
    rest.getMixdown({id: gon.jam_track_mixdown_id})
    .done((response) =>

      for mixdown_package in response.packages
        if mixdown_package.file_type == @props.fileType
          activePackage = mixdown_package

      @setState({mixdown: response, package: activePackage})
    )
    .fail((jqXHR) =>
      alert("Unable to fetch JamTrack information. Try logging in.")
    )

})