#!/usr/bin/perl
package MpdToys;

sub findmatchingsongs {
	my $term=shift;
	my $mpd=shift;

	# pass urls through
	if ($term=~/^(\w+):\/\//) {
		return Audio::MPD::Common::Item->new(file => $term);
	}
	
	my $coll=$mpd->collection;
	
	my $exactmatch=$coll->song($term);
	if ($exactmatch) {
		return $exactmatch;
	}

	my @matches = (
		$coll->songs_from_album_partial($term),
		$coll->songs_by_artist_partial($term),
		$coll->songs_with_title_partial($term),
	);

	return dedupsongs(@matches);
}

sub canmatch_fuzzy {
	eval q{use String::Approx 'amatch'};
	return ! $@;
}

sub findmatchingsongs_fuzzy {
	my $term=shift;
	my $mpd=shift;

	my $coll=$mpd->collection;
	my @matches = (
		(map { $coll->songs_from_album($_) }
			amatch($term, ['i'], $coll->all_albums())),
		(map { $coll->songs_by_artist($_) }
			amatch($term, ['i'], $coll->all_artists()))
	);
	
	# very slow, only try if nothing else matched
	@matches = amatch($term, ['i'], $coll->all_songs())
		if ! @matches;

	return dedupsongs(@matches);
}

sub dedupsongs {
	my %seen;
	my @ret;
	foreach my $song (@_) {
		push @ret, $song unless $seen{$song->file}++;
	}
	return @ret;
}

1
