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


@JamTrackLandingScreen = React.createClass({

  mixins: [Reflux.listenTo(@AppStore,"onAppInit"), Reflux.listenTo(@UserStore, "onUserChanged")]

  cookieName: 'jamtrack_play_search'
  page_amount: 40

  getInitialState: () ->
    {user: null, purchasedJamTracks: []}

  onUserChanged: (userState) ->
    @user = userState?.user
    @onUser(userState.user) if userState.user

  render: () ->

    howTo = null
    if @user?.purchased_jamtracks_count == 0 && @user?.has_redeemable_jamtrack
      howTo =
        `<div className="free-jamtrack">
          <span>
            For a limited time, get one JamTrack free.  Search JamTracks below, add one to your shopping cart, and we'll make it free during the checkout process.
          </span>
        </div>`
    else
      howTo = `<div className="no-free-jamtrack">
        <span>
          The fastest way to start playing with your JamTracks is to open them below and use our <a href="https://jamkazam.freshdesk.com/support/solutions/articles/66000125795-using-jamtracks-in-a-browser" onClick={this.customMixHelpClicked}>custom mix feature</a> to play them back in your browser. To access the full set of JamTrack features, <a href="/downloads" rel="external" onClick={this.downloadsClicked}>install our free app</a>. To learn more about all you can do with JamTracks, check out our <a href="https://jamkazam.freshdesk.com/support/solutions/66000075766" onClick={this.jamTrackHelpClicked}>JamTracks help docs</a>.
        </span>
      </div>`

    playJamTracks = []

    for jamTrack in @state.purchasedJamTracks
      playJamTracks.push `<tr key={jamTrack.id} className="play-jamtrack"><td>
        <a href={JamTrackPlayerStore.createPopupUrl(jamTrack)} target="_blank" onClick={this.onPlayJamTrack.bind(this, jamTrack)}>{jamTrack.name}</a> by {jamTrack.original_artist}</td></tr>`

    if @state.purchasedJamTracks.length < 5
      # fill out the table with empty rows
      for x in [@state.purchasedJamTracks.length...(6 - @state.purchasedJamTracks.length )] by 1
        playJamTracks.push `<tr key={x} ><td>&nbsp;</td></tr>`

    if @state.user?.purchased_jamtracks_count > @page_amount
      autocomplete = `<div className="my-autocomplete"><JamTrackAutoComplete placeholder="Search your JamTracks" onSearch={this.searchMyJamTracks} /><button onClick={this.searchMyJamTracksByString} className="search-by-string-btn button-orange ">SEARCH</button></div>`
    playableJamTracks =
      `<div className="purchased-jam-tracks-holder">
          {autocomplete}
          <div className="purchased-jam-tracks">
          <table className="jamtable" cellSpacing="0" cellPadding="0" border="0">
          <thead>
            <tr><th className="jamtrack-name" align="left">JAMTRACKS</th></tr>
          </thead>
          <tbody>
          {playJamTracks}
          </tbody>
        </table>
        </div>
      </div>`

    `<div className="content-body-scroller">
      <div className="list-columns">
        <div className="browse">
          <h2>my jamtracks</h2>
          <div className="howto">
            {howTo}
            {playableJamTracks}
          </div>
          <h2 className="browse-jamtracks">search jamtracks</h2>
          <div className="search-area">
            <div className="search-help para"> To search by the name of the original artist, band, or song name, enter your search words below:</div>
            <div className="search-controls">
              <JamTrackAutoComplete onSearch={this.search} /><button onClick={this.searchByString} className="search-by-string-btn button-orange ">SEARCH</button>
            </div>
            <div className="filter-help para">To search by genre and instrument, make your selections below:</div>
            <div className="search-controls">
              <select className="genre-list easydropdown" name="genres">
                <option value="">Any Genre</option>
              </select>
              <select className="instrument-list easydropdown" name="insruments">
                <option value="">Any Instrument</option>
              </select>
              <button className="search-by-filter-btn button-orange" onClick={this.searchByFilter}>SEARCH</button>
            </div>
          </div>

          <div className="download-all para">
            Or download the entire JamTracks catalog <JamTrackCSVLink/> or <JamTrackPdfLink/> to easily browse everything we have.
          </div>
        </div>

        <div className="about">
          <h2>what are jamtracks?</h2>
          <div className="what">
            <div className="details">
              JamTracks are the best way to play along with your favorite music!  Unlike traditional backing tracks, JamTracks are professionally mastered, complete multitrack recordings, with fully isolated tracks for each part of the master mix.  Watch the video below to learn more.
            </div>
            <a className="video-thumbnail" href="https://www.youtube.com/watch?v=07zJC7C2ICA" rel="external">
              <img className="play" src="/assets/content/icon_youtube_play.png" />
            </a>
            <a className="ios-appstore-badge" href="https://itunes.apple.com/us/app/jamtracks/id1060927816?ls=1&mt=8">
              <img src="/assets/content/badge-download-on-the-app-store.svg" />
            </a>
          </div>
        </div>
      </div>
    </div>`


  componentDidMount: () ->
    $root = $(@getDOMNode())

  doPurchasedSearch: (searchQuery) ->
    if !searchQuery?
      #searchQuery = $.cookie(@cookieName)

      # and parse that cookie if defined
      if searchQuery
        try
          searchQuery = JSON.parse(searchQuery)
        catch e
          searchQuery = {searchType: 'user-input', searchData: ''}
          logger.error("unable to parse search query: " + e)


    # if still no query (after checking cookie and what was specified in function, then default to anything
    if !searchQuery?
      searchQuery = {searchType: 'user-input', searchData: ''}

    query = {page:1, per_page:@page_amount}

    if searchQuery && searchQuery.searchData && searchQuery.searchData.length > 0 && searchQuery.searchType && searchQuery.searchType.length > 0

      if searchQuery.searchType == 'user-input'
        query.search = searchQuery.searchData
      else if searchQuery.searchType == 'artist-select'
        query.artist_search = searchQuery.searchData
      else if searchQuery.searchType == 'song-select'
        query.song_search = searchQuery.searchData

    rest.getPurchasedJamTracks(query)
    .done((purchasedJamTracks) =>
      if @redeemedFlow
        setTimeout((() => @preparePlayJamTrackProd()), 200)
        @redeemedFlow = false
      @setState({purchasedJamTracks: purchasedJamTracks.jamtracks})
    )
    .fail((jqXHR, textStatus, errorMessage) =>
      @app.ajaxError(jqXHR, textStatus, errorMessage)
    )

  searchMyJamTracks: (searchType, searchData) ->
    searchQuery = {searchType: searchType, searchData: searchData}
    #$.cookie(@cookieName, JSON.stringify(searchQuery))
    @doPurchasedSearch(searchQuery)

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

    @doPurchasedSearch(searchType:'user-input',searchData: window.JamTrackSearchInput)

  search: (searchType, searchData) ->
    context.JamTrackActions.requestSearch(searchType, searchData)

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

    context.JamTrackActions.requestSearch('user-input', window.JamTrackSearchInput)

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

    $root = $(@getDOMNode())
    genre = $root.find('select.genre-list').val()
    instrument = $root.find('select.instrument-list').val()
    context.JamTrackActions.requestFilter(genre, instrument)

  processUrl: () ->

    if $.QueryString['redeemed_flow']?
      @redeemedFlow = true

    if @redeemedFlow

      if window.history.replaceState #ie9 proofing
        window.history.replaceState({}, "", "/client#/jamtrack")

  preparePlayJamTrackProd: () ->
    setTimeout((() =>
      $element = $(this.getDOMNode()).find('.purchased-jam-tracks .play-jamtrack a').first()
      $offsetParent = $element.closest('.screen')

      context.JK.HelpBubbleHelper.jamtrackWebPlay($element, $offsetParent)
    ), 1500)

  afterShow: (data) ->

    @processUrl()

  beforeShow: () ->
    #@setState({user: null})

  onUser:(user) ->
    @setState({user: user})

    if context.JK.currentUserId?
      @doPurchasedSearch()

    # Get artist names and build links
    #@rest.getJamTrackArtists({group_artist: true, per_page:100})
    #.done(this.buildArtistLinks)
    #.fail(this.handleFailure)

    # Bind links to action that will open the jam_tracks list view filtered to given artist_name:
    # artist_name
    #@bindArtistLinks()

  customMixHelpClicked: (e) ->
    e.preventDefault()
    context.JK.popExternalLink($(e.target).attr('href'))

  downloadsClicked:(e) ->
    e.preventDefault()
    context.JK.popExternalLink($(e.target).attr('href'))

  jamTrackHelpClicked: (e) ->
    e.preventDefault()
    context.JK.popExternalLink($(e.target).attr('href'))

  onPlayJamTrack: (jamTrack, e) ->

    if context.jamClient.IsNativeClient()
      e.preventDefault()
      tracks = context.JK.TrackHelpers.getUserTracks(context.jamClient)
      data = {}
      data.client_id = @app.clientId
      #data.description = $('#description').val()
      data.description = "Jam Track Session"
      data.as_musician = true
      data.legal_terms = true
      data.intellectual_property = true
      data.approval_required = false
      data.musician_access = false
      data.fan_access = false
      data.fan_chat = false
      console.log("jamTrack", jamTrack)
      data.genre = $.map(jamTrack.genres, (genre) ->  genre.id)
      data.genres = $.map(jamTrack.genres, (genre)->  genre.id)

      data.genre = ['rock'] if data.genre.length == 0
      data.genres = ['rock'] if data.genres.length == 0
      # data.genres = context.JK.GenreSelectorHelper.getSelectedGenres('#create-session-genre')
      # data.musician_access = if $('#musician-access option:selected').val() == 'true' then true else false
      # data.approval_required = if $('input[name=\'musician-access-option\']:checked').val() == 'true' then true else false
      # data.fan_access = if $('#fan-access option:selected').val() == 'true' then true else false
      # data.fan_chat = if $('input[name=\'fan-chat-option\']:checked').val() == 'true' then true else false
      # if $('#band-list option:selected').val() != ''
      #   data.band = $('#band-list option:selected').val()
      data.audio_latency = context.jamClient.FTUEGetExpectedLatency().latency
      data.tracks = tracks

      rest.legacyCreateSession(data).done((response) =>
        newSessionId = response.id
        context.JK.SessionUtils.setAutoOpenJamTrack(jamTrack) # so that the session screen will pick this up
        context.SessionActions.enterSession(newSessionId)
        # Re-loading the session settings will cause the form to reset with the right stuff in it.
        # This is an extra xhr call, but it keeps things to a single codepath
        #loadSessionSettings()
        context.JK.GA.trackSessionCount data.musician_access, data.fan_access, 0
        context.JK.GA.trackSessionMusicians context.JK.GA.SessionCreationTypes.create
      ).fail (jqXHR) =>
        handled = false
        if jqXHR.status = 422
          response = JSON.parse(jqXHR.responseText)
          if response['errors'] and response['errors']['tracks'] and response['errors']['tracks'][0] == 'Please select at least one track'
            @app.notifyAlert 'No Inputs Configured', $('<span>You will need to reconfigure your audio device.</span>')
            handled = true
        if !handled
          @app.notifyServerError jqXHR, 'Unable to Create Session'

    else
      if true # /iPhone|iPad|iPod|android/i.test(navigator.userAgent)
        # popup window
        JamTrackPlayerActions.opened(jamTrack)

      else
        # popup window
        JamTrackPlayerActions.open(jamTrack)
        e.preventDefault()




  onAppInit: (@app) ->
    @rest = context.JK.Rest()
    @client = context.jamClient
    @logger = context.JK.logger
    @screen = null
    @noFreeJamTrack = null
    @freeJamTrack = null
    @bandList = null
    @noBandsFound = null

    screenBindings =
      'beforeShow': @beforeShow
      'afterShow': @afterShow

    @app.bindScreen('jamtrack', screenBindings)

    @screen = $('#jamtrackLanding')
    @noFreeJamTrack = @screen.find('.no-free-jamtrack')
    @freeJamTrack = @screen.find('.free-jamtrack')
    @bandList = @screen.find('#band_list')
    @noBandsFound = @screen.find('#no_bands_found')

    $root = $(@getDOMNode())
    context.JK.GenreSelectorHelper.render2($root.find('select.genre-list'))

    @instrumentSelector = new context.JK.InstrumentSelector(@app)
    @instrumentSelector.initialize(false, true)
    @instrumentSelector.renderDropdown($root.find('select.instrument-list'))
})