#!/usr/bin/perl -w

use strict;
use Getopt::Long;
use File::Spec;
use File::Basename;
use Module::Load;
use Cwd qw(realpath);
use Carp;

$SIG{ __DIE__ } = sub { Carp::confess( @_ ) };

my $info = 0;
my $debug = 0;
my %config = (
    mode => 'download',
    getter => 'filegetter',
    'plugin.youtube.QUALITY' => 'hd',
    'plugin.filegetter.FILEPATTERN' => './%3$s.flv',
);

sub link_callback {
    my $m = shift;

    if ($info) {
        foreach (keys(%{$m})) {
            printf("%s: %s\n", $_, defined($m->{$_})?$m->{$_}:'(undef)');
        }
        return 1;
    } else {
        print("Downloading $m->{'TITLE'}\n");
        return 0;
    }
}


GetOptions("i" => \$info, "d" => \$debug);

push(@INC, dirname(realpath($0)));
load 'libvideosite';

unless(libvideosite::register_api({
    link_callback => \&link_callback,
    _config_default => sub { return \%config },
    _debug => sub { return $debug },
})) {
    die("Error registering API: $libvideosite::error");
}

unless(libvideosite::init()) {
    die("Could not init libvideosite: $libvideosite::error");
}

foreach (@ARGV) {
    printf("Handling %s...\n", $_);
    libvideosite::check_for_link({
        message => $_,
        io => sub { print @_, "\n" },
        window => "",
    });
}
