#!/usr/bin/env ruby

#
# Use LastFM to find songs from your collection which are similar
# to that currently playing and add them to the MPD playlist.
#

require 'rubygems'
require 'scrobbler'
require 'librmpd'

def more_like_this(n = 10)
  mpd = MPD.new 'localhost', 6600
  mpd.connect

  cur_song = mpd.current_song
  unless cur_song
    puts "Nothing playing!"
    return
  end
  
  cur_artist = cur_song.artist

  puts "Current artist is #{cur_artist}"

  similar = Scrobbler::Artist.new(cur_artist).similar.collect do |a|
     a.name
  end

  mpd_artists = mpd.artists    
  have = similar.select do |a|
    mpd_artists.index a
  end

  puts "Found #{similar.length} similar artists, you have #{have.length}"

  return if have.empty?
  
  songs = have.collect do |a|
    mpd.find('artist', a)
  end.flatten

  #mpd.clear
  n.times do
    mpd.add songs[rand songs.length].file
  end
end

more_like_this ($ARGV.empty? ? 10 : $ARGV[0].to_i)
