#!/usr/bin/perl 

use strict;
use Getopt::Long;

use IMDB::Local;

my ($opt_help,
    $opt_imdbDir,
    $opt_import,
    $opt_quiet,
    $opt_download);
my $opt_title;

GetOptions('help'             => \$opt_help,
	   'imdbdir=s'        => \$opt_imdbDir,
	   'import=s'         => \$opt_import,
	   'quiet'            => \$opt_quiet,
	   'title=s'          => \$opt_title,
    ) or usage(0);

if ( $opt_help ) {
    die "no usage implemented";
}

if ( ! defined($opt_imdbDir) ) {
    die "imdbdir flag is required";
}

$opt_quiet=(defined($opt_quiet));

# lets put list files below the imdbDir
my $listsDir="$opt_imdbDir/lists";

my $db=new IMDB::Local::DB(database=>"$opt_imdbDir/imdb.db");
if ( !$db->connect() ) {
    die "moviedb connect failed:$DBI::errstr";
}

use IMDB::Local::Title;

my $searchableTItle=$db->makeSearchableTitle($opt_title);
print "searching for $searchableTItle\n";

sub DumpTitle($)
{
    my ($t)=@_;

    #my $ind=" " x $index;
    print $t->toText();
    
    if ( $t->QualifierType->Name eq 'tv_series' ) {
	#print "getting episodes..\n";
	
	my $n=0;
	for my $e ($t->getEpisodes()) {
	    $n++;
	    print "=====Episode #$n:\n";
	    $e->populateAll();
	    for (split("\n", $e->toText())) {
		print "\t".$_."\n";
	    }
	    #print $e->toText();
	}
    }
}

my @list=IMDB::Local::Title::findBySearchableTitle($db, $searchableTItle, 0); # any type
for my $i (@list) {
    print "===============================: Title $i\n";

    my $t=IMDB::Local::Title::findByTitleID($db, $i);
    $t->populateAll();
    
    DumpTitle($t);
    
}

exit(0);
