#!/usr/bin/perl

use strict;
use warnings;

use IO::Socket::INET;

### available commands
my @commands = (
   "status"
);

my %connInfo;
$connInfo{"host"} = "localhost";
$connInfo{"port"} = 6600;
$connInfo{"pass"} = "";

sub mpdCommand
{
   my $connInfo = shift;
   my $command = shift;

   my $connection = IO::Socket::INET->new(
      PeerAddr => $connInfo{"host"},
      PeerPort => $connInfo{"port"}
   ) or die "Could not connect to host";

   my ($char, $line, $lines);
   $char = "";

   # Skip first "OK"
   sysread($connection, $char, 1) until $char eq "\n";

   # Send command
   $connection->send($command . "\n");

   my $eof = 0;

   do
   {
      $line = '';

      while (sysread($connection, $char, 1) and $char ne "\n")
      {
         $line .= $char;
      }

      return $lines if $line eq "OK";

      if ($line =~ m/^ACK \[(\d+)@(\d+)\] {(\w*)} (.*)/)
      {
         die $4;
      }

      $lines .= $line . "\n";
   }
   while (1);

   close $connection;

   return $lines;
}

sub mpduniq
{
   my @lines = split("\n", mpdCommand(shift, "playlist"));
   print shift @lines;
}

sub mpdstatus
{
   my $conn = shift;
   my @lines = split("\n", mpdCommand($conn, "status"));
}

mpduniq;
