#!/usr/local/bin/perl 

=head1 NAME

updatedb.pl - a script for creation of new database. 

=head1 SYNOPSIS

updatedb.pl I<file1> I<file2>....


=head1 DESCRIPTION

Updates information in the B<chgk> databse. Uses file


=head1 BUGS

The database, user and password are hardcoded. 

=head1 AUTHOR

Dmitry Rubinstein

=head1 $Id: updatedb.pl,v 1.10 2000/10/20 01:45:46 boris Exp $

=cut

my (%RevMonths) = 
    ('Jan', '1', 'Feb', '2', 'Mar', '3', 'Apr', '4', 'May', '5', 'Jun', '6',
     'Jul', '7', 'Aug', '8', 'Sep', '9', 'Oct', '10', 'Nov', '11',
     'Dec', '12', 
     'JAN', '1', 'FEB', '2', 'MAR', '3', 'APR', '4', 'MAY', '5', 'JUN', '6',
     'JUL', '7', 'AUG', '8', 'SEP', '9', 'OCT', '10', 'NOV', '11',
     'DEC', '12', 
     'Янв', '0', 'Фев', 1, 'Мар', 2, 'Апр', 3, 'Май', '4',
     'Июн', '5', 'Июл', 6, 'Авг', '7', 'Сен', '8', 
     'Окт', '9', 'Ноя', '19', 'Дек', '11');
my ($sth);

use vars qw($/);



use DBI;
use strict;

sub UpdateParents {
    my ($dbh, $ParentId, $all_qnum) = @_;
    if ($ParentId) {
	my ($sth1) = $dbh->prepare("SELECT QuestionsNum, ParentId 
FROM Tournaments WHERE Id = $ParentId");
	$sth1->execute;
	my ($q, $p) = ($sth1->fetchrow)[0, 1];
	$dbh->do("UPDATE Tournaments SET 
                  QuestionsNum=$q + $all_qnum 
                  WHERE Id = $ParentId");
	&UpdateParents($dbh, $p, $all_qnum);
    }
}

sub getField {
    my($desc, $dbh) = @_;
    my($key);
    my($value) = ('');
    while (<$desc>) {
	s///g;
	if ($key && /^\s*$/) {
	    chomp $value;
	    chomp $key;
	    if ($key eq 'Дата') {
		$value =~ s/^(.*)-(.*)-(.*)$/$3-$2-$1/;
		my($month) = $RevMonths{$2} || '000';
		$value =~ s/$2/$month/;
	    }
	    $value = $dbh->quote($value);
	    return ($key, $value);
	}
	next if (/^\s*$/);
	
	if (/^(.*)[:\.][\s]*$/ && !$key) {
	    $key = $1;
	    next;
	}
	if ($key) {
	    $value .= $_;
	    next;
	}
    }
    if ($key && $value) {
	$value = $dbh->quote($value);
	return ($key, $value);
    }
    return (0, 0);
}

sub SelectGroup {
    my ($dbh, $source, $TourName) = @_;
    my ($sth, $ParentId, $i, @arr);
    
    $sth = $dbh->prepare("SELECT Id, Title FROM
		Tournaments WHERE Type = 'Г'");
    $sth->execute;
    print "Выберите группу для турнира:\n$TourName, файл $source\n\n";
    while (@arr=$sth->fetchrow) {
	print "[$arr[0]] $arr[1]\n";
    }
    $ParentId = <STDIN>;
    chomp $ParentId;
    if (!$ParentId) {
	print "Пропускаем файл $source\n";
	print STDERR "Файл $source отвергнут оператором\n";
	return (0,0);
    } else {
	print "Вы выбрали турнир: $ParentId\n";
	$sth = $dbh->prepare("INSERT INTO Tournaments
			      (Title, Type, ParentId, FileName) 
			       VALUES ($TourName, 'Ч', $ParentId, 
                                       $source)");
	$sth->execute;
	my $TournamentId = $sth->{mysql_insertid};
	return ($TournamentId,$ParentId);
    }
		
    
}

sub UpdateTournament {
    my ($dbh, $TournamentId, $field, $value) = @_;
    $dbh->do("UPDATE Tournaments SET $field=$value WHERE Id=$TournamentId")
	or die $dbh->errstr;
}

sub UpdateQuestion {
    my ($dbh, $QuestionId, $field, $value) = @_;
    $dbh->do("UPDATE Questions SET $field=$value 
		WHERE QuestionId=$QuestionId")
	or die $dbh->errstr;
}

sub CheckFile {
    my ($dbh, $source, $title) = @_;
    my $sth = $dbh->prepare("SELECT Id,ParentId,QuestionsNum FROM Tournaments
                             WHERE FileName=$source AND Type='Ч'");
    $sth->execute or die $dbh->errstr;
    my @arr = $sth->fetchrow;
    if (! scalar @arr) {
	return SelectGroup($dbh,$source,$title);
    }
    my($Id,$ParentId,$QuestionsNum)=@arr;
    if($QuestionsNum) {	
	print "Файл $source с данными $title уже существует. ",
	"Заменить?[y/N]\n";
	my $answer = <STDIN>;
	if ($answer !~ /^[yY]/) {
	    return (0,0);
	} else {
	    DeleteTournament($dbh,$Id,$ParentId,$QuestionsNum,0);
	}
    } 
    return($Id,$ParentId);	
}


sub DeleteTournament {
    my ($dbh,$Id,$ParentId,$QuestionsNum,$DeleteMyself) = @_;
    if ($QuestionsNum) {
	UpdateParents($dbh,$ParentId,-$QuestionsNum);
    }
    my (@Tours) = &GetTours($dbh, $Id);
    foreach my $Tour (@Tours) {
	DeleteTournament($dbh,$Tour,1);
    }
    my $sth = $dbh->prepare("DELETE FROM Questions
                             WHERE ParentId=$Id");
    $sth->execute or die $dbh->errstr;
    if($DeleteMyself) {
	$sth = $dbh->prepare("DELETE FROM Tournaments
                             WHERE Id=$Id");
	$sth->execute or die $dbh->errstr;
    }
}

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;
}


MAIN: 
{
    my($key, $value, $addition);
    
    my($source);
    
    my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")
	or die "Can't connect to DB chgk\n";
    
    while ($source = shift) {
	my($PlayedAt) = '';
	my($QuestionId, $TourId, $TournamentId, $ParentId) = (0, 0, 0, 0);
	my($tournum, $qnum, $all_qnum, $qtype) = (0, 0, 0, 'Ч');
	my (@d) = (localtime((stat($source))[9]))[5,4,3];
	$d[1]++;
	$d[0]+=1900;
	my ($CreatedAt) = $dbh->quote( join('-', @d));

	open INFD, $source 
	    or die "Can't open input file: $!\n";
	
	$source =~ s/^.*\/([^\/]*)$/$1/;
	$source = $dbh->quote($source);
	print STDERR "Файл: $source, дата: $CreatedAt ";
	while (($key, $value) = getField(\*INFD, $dbh)) {
	    last if (!$key);
	    
	    if ($key =~ /Мета/) {
		next;   # This is obsolete
	    }
	    if ($key =~ /Чемпионат/ || $key =~ /Пакет/) {		
		($TournamentId, $ParentId) = CheckFile($dbh,$source,$value);
		if (!$TournamentId)  {
		    last;
		}	
		$sth = $dbh->prepare("UPDATE Tournaments SET
			             Title=$value, Type='Ч', 
                                     ParentId=$ParentId, 
                                     FileName=$source, 
                                     CreatedAt=$CreatedAt
                                     WHERE
                                     Id=$TournamentId");
		$sth->execute;
		next;
	    }
	    if ($key =~ /Тур/) {
		if ($TourId) {
		    $dbh->do("UPDATE Tournaments SET QuestionsNum=$qnum
			      WHERE Id=$TourId");
		}
		$qnum = 0;
		$qtype = 'Ч';
		$sth = $dbh->prepare("INSERT INTO Tournaments
				      (Title, Type, ParentId, CreatedAt) 
				      VALUES ($value, 'Т', $TournamentId, 
                                      $CreatedAt)");
		$sth->execute;
		$TourId = $sth->{mysql_insertid};
		next;
	    }
	    if ($key =~ /Вид/ || $key =~ /Тип/) {
		$qtype = $value;
		$qtype =~ s/\'//g;
		next;
	    }
	    if ($key =~ /Вопрос/) {
		my $query = "INSERT INTO Questions 
			     (ParentId, Number, Type) 
			     VALUES ($TourId, $qnum+1, \'$qtype\')";
		$sth = $dbh->prepare($query);
		$sth->execute or print $query;;
		$QuestionId = $sth->{mysql_insertid};
		&UpdateQuestion($dbh, $QuestionId, "Question", $value);
		$qnum++;
		$all_qnum++;
		next;
	    }

	    if ($key =~ /Ответ/) {
		&UpdateQuestion($dbh, $QuestionId, "Answer", $value);
		next;
	    }

	    if ($key =~ /Рейтинг/) {
		&UpdateQuestion($dbh, $QuestionId, "Rating", $value);
		next;
	    }
	    

	    if ($key =~ /Автор/) {
		&UpdateQuestion($dbh, $QuestionId, "Authors", $value);
		next;
	    }
	    

	    if ($key =~ /Источник/) {
		&UpdateQuestion($dbh, $QuestionId, "Sources", $value);
		next;
	    }
	    

	    if ($key =~ /Комментари/) {
		&UpdateQuestion($dbh, $QuestionId, "Comments", $value);
		next;
	    }
	    

	    if ($key =~ /URL/ || $key =~ /Ссылка/) {
		&UpdateTournament($dbh, $TournamentId, "URL", $value);
		next;
	    }
	    

	    if ($key =~ /Копирайт/) {
		&UpdateTournament($dbh, $TournamentId, "Copyright", $value);
		next;
	    }
	    

	    if ($key =~ /Инфо/) {
		&UpdateTournament($dbh, $TournamentId, "Info", $value);
		next;
	    }
	    

	    if ($key =~ /Редактор/) {
		&UpdateTournament($dbh, $TournamentId, "Editors", $value);
		next;
	    }
	    

	    if ($key =~ /Обработан/) {
		&UpdateTournament($dbh, $TournamentId, "EnteredBy", $value);
		next;
			      }
	    
	    if ($key =~ /Дата/) {
		if ($TourId) {
		    &UpdateTournament($dbh, $TourId, "PlayedAt", $value);
		} else {
		    &UpdateTournament($dbh, $TournamentId, "PlayedAt", $value);
		}
		next;
	    }
	    
	    #
	    # If we are here, something got wrong!
	    #
	    print STDERR "\nЯ НЕ ПОНИМАЮ: $key, $value!\n";
	    
	}
	$dbh->do("UPDATE Tournaments SET QuestionsNum=$qnum
			WHERE Id=$TourId");
	$dbh->do("UPDATE Tournaments SET QuestionsNum=$all_qnum
			WHERE Id=$TournamentId");
	&UpdateParents($dbh, $ParentId, $all_qnum);		
	print STDERR "Всего вопросов: $all_qnum \n";
    }
    $dbh->disconnect;
}
