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

=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 are specified the same as they would be to mpc add: As paths to files
in the music database, or urls to stream.

=head1 OPTIONS

=over 4

=item -n

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

=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;
GetOptions(
        "n" => \$shownum,
) || usage();

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

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

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

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

my @out;
foreach my $item (@list) {
	if (! length $item) {
		die "no item specified to insert\n";
	}
	$pl->add($item);
	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);
	}

	push @out, ($pos+1)."\n" if $shownum;
}

@out=reverse@out if $mpd->current;
print $out[0];
