context = window
MIX_MODES = context.JK.MIX_MODES


@JamTrackAutoComplete = React.createClass({

  EVENTS: context.JK.EVENTS
  rest: context.JK.Rest()
  logger: context.JK.logger



  render: () ->

    window.JamTrackSearchInput = '' unless window.JamTrackSearchInput? # can't pass null to react-select

    searchValue = if @state.search == 'SEPARATOR' then '' else window.JamTrackSearchInput

    `<Select
      placeholder={this.props.placeholder}
      name="search-field"
      asyncOptions={this.getOptions}
      autoload={false}
      value={searchValue}
      onChange={this.onSelectChange}
      onBlur={this.onSelectBlur}
      onFocus={this.onSelectFocus}
      className="autocompleter"
      cacheAsyncResults={false}
      filterOption={this.filterOption}
      clearable={false}
      />`

  getDefaultProps: () ->
    {placeholder:'Search for JamTracks'}
  getInitialState: () ->
    ({search: ''})

  filterOption:() ->
    true

  onSelectChange: (val) ->
    #@logger.debug("CHANGE #{val}")

    return false unless val?

    if typeof @props.onSearch is 'string'
      searchFunction = eval(@props.onSearch)
    else
      searchFunction = @props.onSearch

    search_type
    if val.indexOf('ARTIST=') == 0
      search_type = 'artist-select'
      artist = val['ARTIST='.length..-1]
      searchFunction(search_type, artist)
    else if val.indexOf('SONG=') == 0
      search_type = 'song-select'
      song = val['SONG='.length..-1]
      searchFunction(search_type, song)
    else
      @logger.debug("user selected separator")
      # this is to signal to the component that the separator was selected, and it has code in render to negate the selection
      setTimeout((() =>
        @setState({search:val})
      ), 1)

      return false


  onSelectFocus: (e) ->
    e.preventDefault()
    window.JamTrackSearchInput = ''
    @setState({search:''})

  onSelectBlur: (e) ->

    #@logger.debug("blur time")

    #@search()


  getOptions: (input, callback) ->

      #@logger.debug("getOptions input #{input}", this)

      # sigh. ugly global
    window.JamTrackSearchInput = input

    if !input? || input.length == 0
      callback(null, {options: [], complete: false})
      return

    query = {match:input, limit:5}

    if @props.show_purchased_only
      query.show_purchased_only = true

    @rest.autocompleteJamTracks(query)
    .done((autocomplete) =>

      options = []
      for artist in autocomplete.artists
        options.push { value: "ARTIST=#{artist.original_artist}", label: "Artist: #{artist.original_artist}" }

      if options.length > 0 && autocomplete.songs.length > 0
        options.push { value: 'SEPARATOR', label: "---------------"}

      for jamtrack in autocomplete.songs
        options.push { value: "SONG=#{jamtrack.name}", label: "Song: #{jamtrack.name}" }

      callback(null, {options: options, complete: false})
    )
})