module JamRuby
  # not a active_record model; just a search result
  class Search
    attr_accessor :bands, :musicians, :fans, :recordings, :friends

    LIMIT = 10

    # performs a site-white search
    def self.search(query, user_id = nil)

      users = User.search(query, :limit => LIMIT)
      bands = Band.search(query, :limit => LIMIT)
      # NOTE: I removed recordings from search here. This is because we switched
      # to "claimed_recordings" so it's not clear what should be searched.

      friends = Friendship.search(query, user_id, :limit => LIMIT)

      return Search.new(users + bands + friends)
    end

    # performs a friend search scoped to a specific user
    # def self.search_by_user(query, user_id)
    #   friends = Friendship.search(query, user_id, :limit => LIMIT)
    #   return Search.new(friends)
    # end

    # search_results - results from a Tire search across band/user/recording
    def initialize(search_results)
      @bands = []
      @musicians = []
      @fans = []
      @recordings = []
      @friends = []

      if search_results.nil?
        return
      end

      search_results.take(LIMIT).each do |result| 
        if result.class == User
          if result.musician
            @musicians.push(result)
          else
            @fans.push(result)
          end
        elsif result.class == Band
          @bands.push(result)
        elsif result.class == Recording
          @recordings.push(result)
        elsif result.class == Friendship
          @friends.push(result.friend)
        else
          raise Exception, "unknown class #{result.class} returned in search results"
        end     
      end
    end
    
    def self.create_tsquery(query)
      # empty queries don't hit back to elasticsearch
      if query.nil? || query.length == 0
        return nil
      end

      search_terms = query.split

      if search_terms.length == 0
        return nil
      end

      args = nil
      search_terms.each do |search_term|
        if args == nil  
          args = search_term
        else
          args = args + " & " + search_term
        end
        
      end
      args = args + ":*"

      return args
    end

  end
end
