#!/usr/bin/perl                                                                                                       

use DBI;
use Net::CUPS;
use Net::CUPS::Destination;
use Image::ExifTool qw(ImageInfo);

use strict;
use warnings;

use vars qw/$queue/;
require "/usr/lib/gutenbach/config/gutenbach-filter-config.pl" or die "Unable to load configuration";

# Connect to the database
my $db = DBI->connect("dbi:SQLite:dbname=gutenbach.db","","");

# Check to see if table 'queue' exists; if so, drop it
my $queue = $db->selectall_arrayref("SELECT name FROM sqlite_master where name='queue'") or die $DBI::errstr;
my $size = scalar @$queue;
if ($size == 1)
{
    $db->do("drop table queue;") or die $DBI::errstr;
}
elsif ($size > 1)
{
    die "More than one table named 'queue'";
}

# Create table 'queue'
$db->do("create table queue(position INTEGER, job_id TINYTEXT)") or die $DBI::errstr;

my $cups = Net::CUPS->new();
my $printer = $cups->getDestination("sipbmp3");
my @jobs = $printer->getJobs( 0, 0 );
my ($job_ref, $job_id, $attr);

my $jobnum = 0;
my $position = 0;
foreach $job_id(@jobs)
{
    # Insert job_ids into the table with correct positions
    $db->do("insert into queue values($position, '$job_id')") or die $DBI::errstr;
    $position++;

    # $job_exists = $db->selectall_arrayref("SELECT job_id FROM jobs where job_id='$job_id'")

    # $job_ref = $printer->getJob($job_id);
    # my $filepath = "/var/spool/cups/d0$job_ref->{'id'}-001";
    # my $fileinfo = ImageInfo($filepath);
    # my $magic = $fileinfo->{FileType};
    
    # if ($jobnum == 0)
    # {
    # 	print $job_ref->{'user'}." is currently playing:\n";
	
    # 	if ($magic)
    # 	{
    # 	    print "\t".$magic." file ".$job_ref->{'title'}."\n";
    # 	    foreach my $key (qw/Title Artist Album AlbumArtist/)
    # 	    {
    # 		if (exists $fileinfo->{$key})
    # 		{
    # 		    print "\t$fileinfo->{$key}\n";
    # 		}
    # 	    }
    # 	}
    # 	else
    # 	{
    # 	    print "\t".$job_ref->{'title'}."\n";
    # 	}
	
    # 	print "\nComing up the queue:\n\n";
    # }
    # else
    # {
    # 	if ($magic)
    # 	{
    # 	    my $user = $job_ref->{'user'};
    # 	    my $title = $fileinfo->{'Title'};
    # 	    my $artist = $fileinfo->{'Artist'};
    # 	    my $album = $fileinfo->{'Album'};
    # 	    print "$user: \"$title\" by \"$artist\" on \"$album\"\n";
    # 	}
    # 	else
    # 	{
    # 	    my $user = $job_ref->{'user'};
    # 	    my $file = $job_ref->{'title'};
    # 	    print "$user: $file\n";
    # 	}
    # }
    
    # $jobnum += 1;
}

$queue = $db->selectall_arrayref("SELECT * FROM queue") or die $DBI::errstr;
foreach my $row(@$queue)
{
    foreach my $val(@$row)
    {
	print "$val\t";
    }
    print "\n";
}

