#!/usr/bin/perl
use strict;
use warnings;
use Audio::MPD q{0.19.0};
use MpdToys;
use Encode;

=head1 NAME

mpinsert - insert song after currently playing song

=head1 SYNOPSIS

mpinsert [-n] [song ...]

=head1 DESCRIPTION

B<mpinsert> inserts a song (or songs) into the playlist directly after
the currently playing song.

If no songs are specified on the command line, it will read a list from
stdin.

Songs may be specified the same as they would be to mpc add: As paths to
files in the music database, or urls to stream.

You can also enter the name of a playlist, or part of the name of an
album, artist, or song. Matching items will be added to the playlist.

(If the perl String::Approx module is available, it will be used to handle
typos, etc in the names you enter.)

=head1 OPTIONS

=over 4

=item -n

Print the playlist position number that the first song was inserted at.

=back

=item -p

Play the song after inserting it.

=back

=head1 AUTHOR

Copyright 2007-2009 Joey Hess <joey@kitenet.net>

Licensed under the GNU GPL version 2 or higher.

http://kitenet.net/~joey/code/mpdtoys

=cut

use Getopt::Long;
my $shownum=0;
my $playnow=0;
GetOptions(
	"n" => \$shownum,
	"p" => \$playnow,
) || usage();

sub usage {
	die "Usage: mpinsert [-n] [song ...]\n";
}

my @list=@ARGV;
if (! @list) {
	while (<>) {
		chomp;
		push @list, $_;
	}
}
@list=map { decode_utf8($_) } @list;

my $mpd=Audio::MPD->new(conntype => "reuse");
my $pl=$mpd->playlist;

@list=reverse @list if $mpd->current;

my @out;
my $firstsong;
foreach my $item (@list) {
	if (! length $item) {
		die "no item specified to insert\n";
	}

	my @matches=MpdToys::findmatchingsongs($item, $mpd);
	if (! @matches && MpdToys::canmatch_fuzzy()) {
		@matches=MpdToys::findmatchingsongs_fuzzy($item, $mpd);
	}

	foreach my $song (@matches) {
		$pl->add($song->file);
		my @items=$pl->as_items;
		if (! @items) {
			die "failed!";
		}
		my $pos=$#items;
	
		# move from end to just after current
		my $current=$mpd->current;
		if ($current) {
			$pos=$current->pos+1;
			$pl->move($#items, $pos);
		}
	
		$firstsong=$pos unless defined $firstsong;
		push @out, ($pos+1) if $shownum;
	}
}

if ($shownum) {
	@out=reverse @out if $mpd->current;
	print $out[0]."\n" if @out;
}
if ($playnow && defined $firstsong) {
	$mpd->play($firstsong);
}
