#!perl  
use DBI;
@months=('000','Jan',"Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct",
          "Nov","Dec");

$fname=shift;
$fname=~s/\.txt$//;
$TMPDIR="new";
    my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")
	or die "Can't connect to DB chgk\n";

   if (WriteFile($dbh,$fname)==-1) {print "File?";}

   $dbh->disconnect;


sub PrintDate {
  my $date=shift;
  my ($year,$month,$day)=split /-/, $date;
#  $month=0,$date=0 if $year && $month==1 && $day==1;
  return sprintf("%02d-%3s-%04d",$day,$months[$month],$year);
}

sub WriteFile {
  my ($dbh,$fname) = @_;
  $fname=~s/\.txt$//;
  $fname=~s/.*\/(\w+)/$1/;
  my $query= "SELECT Id, Title, Copyright, Info, URL, 
                      Editors, EnteredBy, PlayedAt, CreatedAt 
                     from Tournaments where FileName=".$dbh->quote("$fname.txt");
  my $sth=$dbh->prepare($query);
  my (%Question,%editor,%qnumber,%copyright,%author,%vid,%tourtitle,%info);
  $sth->execute;
  my ($Id, $Title, $Copyright, $Info, $URL, 
   $Editors, $EnteredBy, $PlayedAt, $CreatedAt)=
      $sth->fetchrow;
  return -1 unless $Id;
  open (OUT, ">$TMPDIR/$fname.txt");
  print OUT "Чемпионат:\n$Title\n\n";

  print OUT "URL:\n$URL\n\n" if $URL;

  print OUT "Инфо:\n$Info\n\n" if $Info;

  print OUT "Копирайт:\n$Copyright\n\n" if $Copyright;

  print OUT "Редактор:\n$Editors\n\n" if $Editors;

  print OUT "Дата:\n".PrintDate($PlayedAt)."\n\n" if $PlayedAt;

  print OUT "Обработан:\n$EnteredBy\n\n" if $EnteredBy;


  $query= "SELECT Id, Title, Copyright, Editors, PlayedAt, Info from Tournaments where ParentId=$Id order by Id";
  $sth=$dbh->prepare($query);
  $sth->execute;
  my ($tourid,$tourtitle,$cright,$editor,@tours,$vid,$author,$tourauthor);


  while (($tourid,$tourtitle,$cright,$editor,$date,$info)=$sth->fetchrow,$tourid)
  {
#    $text{$tourid}="Тур:\n$tourtitle\n\n";
    $query= "SELECT * from Questions where ParentId=$tourid order by QuestionId";
    my $sth1=$dbh->prepare($query);
    $sth1->execute;
    push(@tours,$tourid);
    $tourtitle{$tourid}=$tourtitle;
    $copyright{$tourid}=$cright;
    $info{$tourid}=$info;
    $editor{$tourid}=$editor;
    $date{$tourid}=$date if $date;
    $vid='';
    my $author='';
    my $eqauthor=1;
    my $qnumber=0;
    my @arr;
    while ( @arr=$sth1->fetchrow, $arr[0])
    {
	my $i = 0;
	$qnumber++;

	foreach my $name (@{$sth1->{NAME}}) {
	        $arr[$i]=~s/^(.*?)\s*$/$1/ if $arr[$i];
		$Question{$tourid}[$qnumber]{$name} = $arr[$i++];
	}
	if ($vid)
        {
          if ($vid ne $Question{$tourid}[$qnumber]{'Type'}) {print STDERR "Warning: Different types for Tournament $tourid\n"}
        } else 
        {
            $vid=$Question{$tourid}[$qnumber]{'Type'};
        } 


	if ($author)
        {
          if ($author ne $Question{$tourid}[$qnumber]{'Authors'})  
          {
             $eqauthor=0;
          }
        } else 
        {
            $author=$Question{$tourid}[$qnumber]{'Authors'};
            $eqauthor=0 unless $author;
        } 
    }
    $vid{$tourid}=$vid;
    $qnumber{$tourid}=$qnumber;
    $author{$tourid}=$eqauthor ? $author : '';
  }


  $vid='';
  my $eqvid=1;
  my $eqauthor=1;
  my $eqdate=1;
  my $eqinfo=1;
  $date='';


  foreach (@tours)
  {
     $vid||=$vid{$_};
     if ($vid{$_} ne $vid)
     {
        $eqvid=0;
     }
     $author||=$author{$_};
     if (!$author{$_} || ($author{$_} ne $author))
     {
        $eqauthor=0;
     }
     $date||=$date{$_};
     if (!$date{$_} || ($date{$_} ne $date))
     {
        $eqdate=0;
     }
     $info||=$info{$_};
     if (!$info{$_} || ($info{$_} ne $info))
     {
        $eqinfo=0;
     }

  }
  print OUT "Вид:\n$vid\n\n" if $eqvid;
  print OUT "Автор:\n$author\n\n" if $eqauthor;

  foreach my $tour(@tours)
  {
     print OUT "Тур:\n$tourtitle{$tour}\n\n";
     print OUT "Вид:\n$vid{$tour}\n\n" if  !$eqvid;
     print OUT "Копирайт:\n$copyright{$tour}\n\n" if $copyright{$tour} && ($copyright{$tour} ne $Copyright);
     print OUT "Редактор:\n$editor{$tour}\n\n" if $editor{$tour} && ($editor{$tour} ne $Editors);
     print OUT "Дата:\n".PrintDate($date{$tour})."\n\n" if $date{$tour} && (!$eqdate  || !$PlayedAt || $PlayedAt ne $date{$tour});
     print OUT "Инфо:\n$info{$tour}\n\n" if $info{$tour} && (!$eqinfo  || !$Info || $Info ne $info{$tour});
     $tourauthor=0;
     if (!$eqauthor && $author{$tour})
     { 
       print OUT "Автор:\n$author{$tour}\n\n";
       $tourauthor=1;
     }
     foreach my $q(1..$qnumber{$tour})
     {
        print OUT "Вопрос $q:\n".$Question{$tour}[$q]{'Question'}."\n\n";
	print OUT  "Ответ:\n".$Question{$tour}[$q]{'Answer'}."\n\n";
	print OUT  "Автор:\n".$Question{$tour}[$q]{'Authors'}."\n\n" 
               if !$tourauthor && !$eqauthor && $Question{$tour}[$q]{'Authors'};
	print OUT  "Комментарий:\n".$Question{$tour}[$q]{'Comments'}."\n\n" 
               if $Question{$tour}[$q]{'Comments'};
	print OUT "Источник:\n".$Question{$tour}[$q]{'Sources'}."\n\n" 
               if $Question{$tour}[$q]{'Sources'};
	print OUT "Рейтинг:\n".$Question{$tour}[$q]{'Rating'}."\n\n" 
               if $Question{$tour}[$q]{'Rating'};

     }
  }

  close OUT;



}


