#!/usr/local/bin/perl -w

=head1 NAME

createindex.pl - a script for creation of index of the database

=head1 SYNOPSIS

createindex.pl [B<-h]] | [B<-o> I<output_file>]


=head1 DESCRIPTION

This script will dump the current information about tournaments 
tree to the standard output or I<output_file> in the format
  į|I<file> N*tabstops  I<Name>

where į is for groups, I<file> is for packages, N is the depth+2, I<Name>
is the name of the group/tournament

=head1 BUGS

The database, user and password are hardcoded. 

=head1 AUTHOR

Boris Veytsman

=head1 $Id: createindex.pl,v 1.2 2000/10/18 18:46:30 boris Exp $

=cut


    use DBI;
use strict;
use vars qw($opt_o $opt_h);
use Getopt::Std;

my $USAGE="Usage: createindex.pl -o output_file\n";

getopts('ho:') or die $USAGE;
if($opt_h) 
{
    print $USAGE;
    exit 0;
}
if($opt_o) 
{
    open (OUT, ">$opt_o") or die "Cannot open $opt_o";
    select OUT;
}

my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "") 
    or die "Cannot connect!";

PrintAll($dbh,0,0);

$dbh->disconnect;
exit 0;

sub PrintAll {
    my ($dbh, $Id, $depth) = @_;
    my (%Tournament) = &GetTournament($dbh, $Id);
    my (@Tours) = &GetTours($dbh, $Id);
    if ($Id) {
	if ($Tournament{'Type'} eq 'į') {
	    for (my $i=0; $i<$depth; $i++) {
		print "\t";
	    }
	    print $Tournament{'Title'}, "\n";
	    for (my $i = 0; $i < scalar @Tours; $i++) {
		PrintAll($dbh, $Tours[$i],$depth+1);
	    } 
	} else {
	    print $Tournament{'FileName'};
	    my $length = 12 -length($Tournament{'FileName'});
	    for (my $i=0; $i<$length; $i++) {
		print " ";
	    }
	    for (my $i=1; $i<$depth; $i++) {
		print "\t";
	    }
	    print $Tournament{'Title'}, "\n";
	}
    } else {
	for (my $i = 0; $i < scalar @Tours; $i++) {
	    PrintAll($dbh, $Tours[$i],$depth+1);
	}
} 
	
}



sub GetTournament {
	my ($dbh, $Id) = @_;
	my (%Tournament, $field, @arr);

	return %Tournament if ($Id == 0);

	my ($sth) = $dbh->prepare("SELECT * FROM Tournaments WHERE Id=$Id");
	$sth->execute;

	@arr = $sth->fetchrow;
	my($i, $name) = 0;
	foreach $name (@{$sth->{NAME}}) {
		$Tournament{$name} = $arr[$i++];
	}

	return %Tournament;
}

sub GetTours {
	my ($dbh, $ParentId) = @_;
	my (@arr, @Tours);

	my ($sth) = $dbh->prepare("SELECT Id FROM Tournaments
		WHERE ParentId=$ParentId ORDER BY Id");

	$sth->execute;

	while (@arr = $sth->fetchrow) {
		push @Tours, $arr[0];
	}

	return @Tours;
}

