context = window
MIX_MODES = context.JK.MIX_MODES


@JamTrackFilterScreen = React.createClass({

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

  LIMIT: 20
  instrument_logo_map: context.JK.getInstrumentIconMap24()

  render: () ->

    searchText = if @state.first_search then 'SEARCH' else 'SEARCH AGAIN'

    uiJamTracks = []
    for jamtrack in @state.jamtracks
      trackRow = context._.clone(jamtrack)
      trackRow.track_cnt = jamtrack.tracks.length
      trackRow.tracks = []

      # if an instrument is selected by the user, then re-order any jam tracks with a matching instrument to the top

      instrument = @instrument.val() if @instrument?
      if instrument?
        jamtrack.tracks.sort((a, b) =>
          aWeight = @computeWeight(a, instrument)
          bWeight = @computeWeight(b, instrument)
          return aWeight - bWeight
        )

      for track in jamtrack.tracks

        if track.track_type == 'Master' || track.track_type == 'Track'
          trackRow.tracks.push(track)
          if track.track_type == 'Master'
            track.instrument_desc = "Master"
          else if track.track_type == 'Track'
            inst = '../assets/content/icon_instrument_default24.png'
            if track.instrument?
              if track.instrument.id in @instrument_logo_map
                inst = @instrument_logo_map[track.instrument.id].asset
              track.instrument_desc = track.instrument.description
            track.instrument_url = inst

            if track.part != ''
              track.instrument_desc += ' (' + track.part + ')'

      trackRow.free_state = if (@state.is_free && jamtrack.allow_free) then 'free' else 'non-free'

      trackRow.is_free = @state.is_free && jamtrack.allow_free

      uiJamTracks.push trackRow


    jamtracks = []


    for jamtrack in uiJamTracks

      jamtrackPricesClasses = { "jamtrack-price" : true }
      jamtrackPricesClasses[jamtrack.free_state] = true
      jamtrackPricesClasses = classNames(jamtrackPricesClasses)

      tracks = []
      for track in jamtrack.tracks
        tracks.push `<div className="jamtrack-track hidden" key={track.id} data-jamtrack-track-id={track.id}>
          <div className="jamtrack-preview">
            <JamTrackPreview jamTrack={jamtrack} jamTrackTrack={track} options={{master_shows_duration: true, color:'gray'}} />
            <div className="clearall" />
          </div>
        </div>`

      actionBtn = null
      if jamtrack.purchased
        if jamtrack.can_download
          actionBtn = `<a className="jamtrack-add-cart-disabled button-grey button-disabled" href="javascript:void(0)">PURCHASED</a>`
        else
          priceNotice = `<div className={jamtrackPricesClasses}>$ {Number(jamtrack.upgrade_price).toFixed(2)}</div>`
          actionBtn = `<div>
            <div className="jamtrack-add-zone">
              {priceNotice}
              <a className="jamtrack-add-cart button-orange" href="#" data-jamtrack-id={jamtrack.id} data-variant="download">UPGRADE TO FULL</a>
            </div>
            <a className="jamtrack-upgrade-help" href='#'>HELP</a>
          </div>`


      else if jamtrack.is_free
        actionBtn = `<a className="jamtrack-add-cart button-orange is_free" href="#" data-jamtrack-id={jamtrack.id} data-variant="full">GET IT FREE!</a>`
      else if jamtrack.added_cart
        actionBtn = `<a className="jamtrack-add-cart-disabled button-grey button-disabled" href="client#/shoppingCart">ALREADY IN CART</a>`
      else
        priceNotice = `<div className={jamtrackPricesClasses}>$ {jamtrack.price}</div>`
        fullPriceNotice = `<div className={jamtrackPricesClasses}>$ {jamtrack.download_price}</div>`
        actionBtn = `<div>
          <div className="jamtrack-add-zone">
            {priceNotice}
              <a className="jamtrack-add-cart button-orange" href="#" data-jamtrack-id={jamtrack.id} data-variant="stream">ADD TO CART</a>
          </div>
          <div className="jamtrack-add-zone">
            {fullPriceNotice}
            <a className="jamtrack-add-cart button-orange" href="#" data-jamtrack-id={jamtrack.id} data-variant="full">ADD TO CART (FULL)</a>
          </div>
          <a className="jamtrack-variant-help" href='#'>HELP</a>
        </div>`

      availabilityNotice = null
      if jamtrack.sales_region==context.JK.AVAILABILITY_US
        availabilityNotice =
          `<div className="jamtrack-license">
            This JamTrack available only to US customers. &nbsp;&nbsp;&nbsp;&nbsp;
            <a className="license-us-why" href="#">why?</a>
          </div>`

      jamtracks.push `<tr className="jamtrack-record" key={jamtrack.id} data-jamtrack-id={jamtrack.id}>
        <td className="jamtrack-detail">
          <div className="jamtrack-name">"{jamtrack.name}"</div>
          <div className="jamtrack-original-artist"><a onClick={this.onArtistClick.bind(this, jamtrack.original_artist)}>by {jamtrack.original_artist}</a></div>
          <br className="clearall"/>
          <div className="clearall detail-label extra hidden song-writer">Songwriters:</div>
          <div className="detail-value extra hidden">{jamtrack.songwriter}</div>
          <div className="clearall detail-label extra hidden">Publishers:</div>
          <div className="detail-value extra hidden">{jamtrack.publisher}</div>
          <div className="clearall detail-label extra hidden">Genres:</div>
          <div className="detail-value extra hidden">{jamtrack.genres.join(', ')}</div>
          <div className="clearall detail-label extra hidden">Version:</div>
          <div className="detail-value extra hidden">{jamtrack.recording_type}</div>
        </td>
        <td className="jamtrack-tracks">
          <div className="detail-arrow">
            <div className="jamtrack-detail-btn">
              show all tracks <a className="details-arrow arrow-down"/>
            </div>
          </div>
          {tracks}
        </td>
        <td className="jamtrack-action">
          <div className="jamtrack-action-container">
            <div className="jamtrack-actions">
              {actionBtn}
              {availabilityNotice}
            </div>
          </div>

        </td>
      </tr>`

    if @state.searching
      jamtracksHeader = "searching..."
    else
      jamtracksHeader = "search results: #{@state.count} jamtracks"

    jamTracksSection =
      `<div>
        <h2 className="jamtrack-results-header">{jamtracksHeader} <a className="back-to-jamtracks-home" href="/client#/jamtrack">back to jamtracks home</a></h2>
        <table className="generaltable jamtrack-table">
          <thead>
          <tr>
            <th className="jamtrack-detail">JAMTRACK</th>
            <th className="jamtrack-tracks">TRACKS INCLUDED / PREVIEW</th>
            <th className="jamtrack-shop">SHOP</th>
          </tr>
          </thead>
          <tbody className="jamtrack-content">
          {jamtracks}
          </tbody>
        </table>
        <div className="end-of-jamtrack-list end-of-list">No more JamTracks</div>
      </div>`

    options = {}

    `<div className="JamTrackFilterScreen">
      <div className="content-body-scroller">
        {jamTracksSection}
      </div>
    </div>`

  clearResults:() ->
    #@content.empty()
    #@noMoreJamtracks.hide()
    @setState({currentPage: 0, next: null, jamtracks:[], type: 'user-input', searching:false, is_free: @user.show_free_jamtrack})

  getInitialState: () ->
    {search: '', type: 'user-input', jamtracks:[], show_all_artists: false, currentPage: 0, next: null, searching: false, count: 0, is_free: context.JK.currentUserFreeJamTrack}

  onArtistClick: (artist, e) ->
    e.preventDefault()

    context.JamTrackActions.requestSearch('artist-select', artist)

  defaultQuery:(extra) ->
    query =
      per_page: @LIMIT
      page: @state.currentPage + 1
    if @state.next
      query.since = @state.next

    instrument = @instrument.val()
    if instrument?
      query.instrument = instrument

    genre = @genre.val()
    if genre?
      query.genre = genre

    $.extend(query, extra)

  userSearch: (e) ->
    e.preventDefault()
    @search()

  setFilterState: (state) ->
    if state
      @genre.easyDropDown('enable').removeAttr('disabled')
      @instrument.easyDropDown('enable').removeAttr('disabled')
    else
      @genre.easyDropDown('disable').attr('disabled', 'disabled')
      @instrument.easyDropDown('disable').attr('disabled', 'disabled')


  search: (search_type, input) ->
    return if @state.searching

    $root = $(@getDOMNode())
    # disable scroll watching now that we've started a new search
    $root.find('.content-body-scroller').off('scroll')
    $root.find('.end-of-jamtrack-list').hide()


    # we have to make sure the query starts from page 1, and no 'next' from previous causes a 'since' to show up
    query = @defaultQuery({page: 1})
    delete query.since
    @rest.getJamTracks(query)
    .done((response) =>
      @setState({jamtracks: response.jamtracks, next: response.next, searching: false, first_search: false, currentPage: 1, count: response.count})
    )
    .fail((jqXHR) =>
      @app.notifyServerError jqXHR, 'Search Unavailable'
      @setState({searching: false, first_search: false})
    )


    @setState({currentPage: 0, next: null, jamtracks:[], searching: true, count: 0})

  componentDidMount: () ->
    $screen = $('#jamtrackFilter')
    @genre = $screen.find('#jamtrack_genre')
    @instrument = $screen.find('#jamtrack_instrument')

    @genre.on 'change', this.userSearch
    @instrument.on 'change', this.userSearch

    # increase dropdown size
    context.JK.dropdown(@genre, {cutOff:15})
    context.JK.dropdown(@instrument, {cutOff:15})


  componentDidUpdate: ( ) ->
    $root = $(this.getDOMNode())
    $scroller = $root.find('.content-body-scroller')

    @setFilterState(!@state.searching)

    for jamTrack in @state.jamtracks
      jamtrackElement = $root.find("tbody .jamtrack-record[data-jamtrack-id=\"#{jamTrack.id}\"]")
      alreadyRegistered = jamtrackElement.data('registered')

      unless alreadyRegistered
        jamtrackElement.data('jamTrack', jamTrack)
        jamtrackElement.data('expanded', true)
        jamtrackElement.data('registered', true)

        @handleExpanded(jamtrackElement)
        @registerEvents(jamtrackElement)


    if @state.next == null
      $scroller = $root.find('.content-body-scroller')
      # if we less results than asked for, end searching
      #$scroller.infinitescroll 'pause'
      $scroller.off('scroll')
      if @state.currentPage == 1 and @state.jamtracks.length == 0
        $root.find('.end-of-jamtrack-list').text('No JamTracks found matching your search').show()
        @logger.debug("JamTrackSearch: empty search")
      else if @state.currentPage > 0
        $noMoreJamtracks = $root.find('.end-of-jamtrack-list').text('No more JamTracks').show()
        # there are bugs with infinitescroll not removing the 'loading'.
        # it's most noticeable at the end of the list, so whack all such entries
    else
      @registerInfiniteScroll($scroller)



  registerInfiniteScroll:($scroller) ->
    $scroller.off('scroll')
    $scroller.on('scroll', () =>

      # be sure to not fire off many refreshes when user hits the bottom
      return if @refreshing

      if $scroller.scrollTop() + $scroller.innerHeight() + 100 >= $scroller[0].scrollHeight
        $scroller.append('<div class="infinite-scroll-loader-2">... Loading more JamTracks ...</div>')
        @refreshing = true
        @logger.debug("refreshing more jamtracks for infinite scroll")
        @setState({searching:true})
        @rest.getJamTracks(@defaultQuery())
        .done((json) =>
          @setState({jamtracks: @state.jamtracks.concat(json.jamtracks), next: json.next, currentPage: @state.currentPage + 1, count: json.count})
        )
        .always(() =>
          $scroller.find('.infinite-scroll-loader-2').remove()
          @refreshing = false
          @setState({searching: false})
        )
    )

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

  addToCartJamtrack:(e) ->
    e.preventDefault()
    $target = $(e.target)
    params = id: $target.attr('data-jamtrack-id')
    params.variant = $target.attr('data-variant')
    isFree = $(e.target).is('.is_free')

    @rest.addJamtrackToShoppingCart(params).done((response) =>
      if response.fast_reedem
        if context.JK.currentUserId?
          context.location = '/client#/redeemComplete'
        else
          context.location = '/client#/redeemSignup'
      else
        context.location = '/client#/shoppingCart'

    ).fail(() => @app.ajaxError)

  licenseUSWhy:(e) ->
    e.preventDefault()
    @app.layout.showDialog 'jamtrack-availability-dialog'

  registerEvents:($parent) ->
    $parent.find('.play-button').on 'click', @playJamtrack
    $parent.find('.jamtrack-add-cart').on 'click', @addToCartJamtrack
    $parent.find('.license-us-why').on 'click', @licenseUSWhy
    $parent.find('.jamtrack-detail-btn').on 'click', @toggleExpanded
    $parent.find('.jamtrack-variant-help').on 'click', @showVariantHelp
    $parent.find('.jamtrack-upgrade-help').on 'click', @showUpgradeHelp

  showVariantHelp: (e) ->
    $screen = $('#jamtrackFilter')
    e.preventDefault()
    context.JK.HelpBubbleHelper.jamtrackVariants($(e.target), $screen)

  showUpgradeHelp: (e) ->
    $screen = $('#jamtrackFilter')
    e.preventDefault()
    context.JK.HelpBubbleHelper.jamtrackUpgrade($(e.target), $screen)

  toggleExpanded:(e) ->
    e.preventDefault()
    jamtrackRecord = $(e.target).parents('.jamtrack-record')
    @handleExpanded(jamtrackRecord)

  handleExpanded:(trackElement) ->
    jamTrack = trackElement.data('jamTrack')
    expanded = trackElement.data('expanded')
    expand = !expanded
    trackElement.data('expanded', expand)

    detailArrow = trackElement.find('.jamtrack-detail-btn')

    if expand
      trackElement.find('.extra').removeClass('hidden')
      detailArrow.html('hide tracks <a class="details-arrow arrow-up"></a>')
      for track in jamTrack.tracks
        trackElement.find("[data-jamtrack-track-id='#{track.id}']").removeClass('hidden')
    else
      trackElement.find('.extra').addClass('hidden')
      detailArrow.html('show all tracks <a class="details-arrow arrow-down"></a>')
      count = 0
      for track in jamTrack.tracks
        if count < 6
          trackElement.find("[data-jamtrack-track-id='#{track.id}']").removeClass('hidden')
        else
          trackElement.find("[data-jamtrack-track-id='#{track.id}']").addClass('hidden')
        count++


  afterShow: (data) ->
    @setFilterFromURL()

  beforeShow: () ->
    @setState({is_free: context.JK.currentUserFreeJamTrack})

  setFilterFromURL:()  ->

    performSearch = false
    if $.QueryString['genre']?
      performSearch = true
      @genre.easyDropDown('select', $.QueryString['genre'], true)
    if $.QueryString['instrument']?
      performSearch = true
      @instrument.easyDropDown('select', $.QueryString['instrument'], true)

    unless performSearch
      search = context.JamTrackStore.checkRequestedFilter()
      if search?
        performSearch = true
        @genre.easyDropDown('select', search.genre, true)
        @instrument.easyDropDown('select', search.instrument, true)

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

  onAppInit: (@app) ->

    window.JamTrackSearchInput = '' # need to be not null; otherwise react-select chokes
    @EVENTS = context.JK.EVENTS
    @rest = context.JK.Rest()
    @logger = context.JK.logger

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

    @app.bindScreen('jamtrack/filter', screenBindings)

  onUserChanged: (userState) ->
    @user = userState?.user
    @setState({is_free: @user?.show_free_jamtrack})

  computeWeight: (jam_track_track, instrument) ->
    weight = switch
      when jam_track_track.track_type == 'Master' then 0
      when jam_track_track.instrument?.id == instrument then 1 + jam_track_track.position
      else 10000 + jam_track_track.position

})