package Templates::CommentsTL;

use SmallPigVars qw($config);
use Templates::Default;

use strict;
use vars qw(@ISA $template);

@ISA = qw(Templates::Default);

my $lang;

sub new{
  my ($class, $spcgi, $spdb, $pagetype) = @_;

  $template = Templates::Default->new($spcgi, $spdb, $pagetype);

  $template->{'spcgi'} = $spcgi;
  $template->{'STATE'} = $spcgi->{'STATE'};
  $template->{'spdb'} = $spdb || SPDB->new;
  
  bless $template, $class;

  $template->initialize();
  
  return $template;
}

#########################################################################
# --- Sun Dec 19 23:06:10 PST 1999
# ---
sub initialize{
  my ($template) = @_;
  
  my $pagefiles = {};
  $pagefiles->{'default'} = "default.temp";
  
  $template->{'pagefiles'} = $pagefiles;

  my $pagesubs = {};
#  $pagesubs->{'default'} = \&whole;
  
  $template->{'pagesubs'} = $pagesubs;

  $lang = $template->{'lang'};

#  $template->{'mconfig'} = $template->_get_mconfig();
}

sub print_topicslist{
    my ($template) = @_;
    
    $template->print_block_start();
    
    $template->print_topicslist_helper();
    
    $template->print_block_end();      
}

sub print_topicslist_helper{
  my ($template) = @_;
  my $spdb = $template->{'spdb'};
  my $STATE = $template->{'STATE'};
  my $DBH = $spdb->{'dbh'};
  my $topics = $template->{'tlptr'};
  my $theme = $template->{'theme'};

 my ($page, $postsper, $sid, $cid, $view, $sort, $op, $mode, $nps, $uid) = 
    map{ $STATE->{$_} } 
  qw|page postsper sid cid view sort op mode nps uid|;

  unless($mode eq "printable"){
      my ($subject, $poster, $lastpost, $date) =
	  (($sort eq "subject asc")?"subject desc":"subject asc",
	   ($sort eq "nickname asc")?"nickname desc":"nickname asc",
	   ($sort eq "lastmod asc")?"lastmod desc":"lastmod asc",
	   ($sort eq "date asc")?"date desc":"date asc");
      
      my $cgi;
      $cgi = $ENV{'SCRIPT_NAME'};
      
      $subject = $template->url_encode("$subject");
      $poster = $template->url_encode("$poster");
      $lastpost = $template->url_encode("$lastpost");
      $date = $template->url_encode("$date");
      
      my $url;
      $url = "$cgi?op=$op&page=$page&postsper=$postsper&sort=";
      
      my $str;
      $str = "<A class=bheader HREF=$config->{'basewwwdir'}$url";
      $sid = $template->url_encode($sid);
      my $end = "&sid=$sid&view=$view";
      
      my $replies_field = "&nbsp;";
      $replies_field = $lang->{'replies'};
      print qq!
<TR BGCOLOR=$theme->{'dhdrcolor'} CELLPADDING=2>
<TD WIDTH=$theme->{'csubject_w'} CLASS=bheader2>$str$subject$end>$lang->{'subject'}</A></TD>
<TD WIDTH=$theme->{'cuser_w'} CLASS=bheader2>$str$poster$end style="color:$theme->{'bhdr2fontcolor'};">$lang->{'posted_by'}</A></TD>!;
      
      # --- if view is collapsed
      if(!$view || $view eq "collapsed"){
	  print qq!
<TD WIDTH=$theme->{'creplies_w'} CLASS=bheader2>$replies_field</TD>
<TD WIDTH=$theme->{'clastmod_w'} CLASS=bheader2>$str$lastpost$end style="color:$theme->{'bhdr2fontcolor'};">$lang->{'lastmod'}</A></TD>!;
      }
      # --- elsif is expanded
      else{
	  print qq!
<TD WIDTH=$theme->{'edate_w'} CLASS=bheader2>$str$date$end\ style="color:$theme->{'bhdr2fontcolor'};">$lang->{'date'}</A></TD>!;
    }
      print "</TR>";
  }

  if($topics){

      my $color = 0;
      while (my ($sid, $cid, $uid) = $topics->fetchrow_array){

	  # --- if view is collapsed
	  if($view eq "collapsed"){
	      print_collapsed_thread_info($STATE, $cid, "", $color);
	      $color = ($color == 0)?1:0;			  
	  }
	  # --- else is expanded
	  else{
	      $template->print_expanded_thread_info($STATE, $cid, "", $color);
	      $color = ($color == 0)?1:0;	
	      $color = $template->_print_subthreads_info($cid, 1, $color); 
	  }
	  
      }
      
      $spdb->db_handler_done($topics);

  }
  else{
      print qq!
	  <TR><TD COLSPAN=4>$lang->{'no_posts'}\!</TD></TR>
	      !;
  }
}

#############################################################################
# --- private functions
# ---
#############################################################################
sub _list_ptr{
  my ($template) = @_;
  my $STATE = $template->{'STATE'};
  my $spdb = $template->{'spdb'};
  my $DBH = $spdb->{'dbh'};

  my ($page, $postsper, $sid, $cid, $view, $sort, $op, $mode, $nps, $uid) = 
      map{ $STATE->{$_} } 
  qw|page postsper sid cid view sort op mode nps uid|;

  $page ||= 1;
  $sort ||= $config->{'sort'};
  $postsper ||= $config->{'postsper'};

  my $sid_q = $DBH->quote($sid);
  my $select = "P.sid, P.cid, P.uid";

  my $from = "Posts AS P";
  my $where = "P.sid=$sid_q " if defined($sid);

  if($mode eq "shownewposts"){

      if(!$nps){ return undef; }

      my $tmp; my $flag=0;
      my @tmp = split(/\,/, $nps);
      foreach (@tmp){
	  my ($pid) = $template->_select_the_most_parent($_);
	  if($pid){ $_ = $pid; }
	  $tmp .= "P.cid=$_ OR "; $flag = 1;
      }
      $tmp =~ s/OR $//;
      $where .= " AND ($tmp) " if $flag;
  }
  
  # --- display the most parent threads 
  $from .= ", MostParents AS MP ";
  $where .= "AND MP.cid=P.cid ";
  $where .= "AND approved=1 ";
  
  my $tmp = $sort;

  # -------------------------------------------------------------- #
  # --- Sat Nov 20 23:35:39 PST 1999

  if($tmp =~ /name/){
      $from .= ",Users AS U ";
      $where .= "AND P.uid=U.uid "; 
  }

  # -------------------------------------------------------------- #

  $tmp =~ s/date/lastmod/ if $from =~ /MostParents/;
  my $others = "ORDER BY $tmp ";
  my $tmplimit = $postsper;
  if($page == 1){
      $others .= "LIMIT $tmplimit";
  }
  else{ 
      my $tmpstart = ($page-1)*$tmplimit; 
      $others .= "LIMIT $tmpstart, $tmplimit";
  }

  # --- select the topics
  my ($topics, $totalnums) = $spdb->db_select_many_new(1, 
						       $select, $from, $where, 
						       $others);
  # --- get the totalnums
  my $totalnums = $spdb->db_count($from, $where);
  
  return ($topics, $totalnums);
}

sub _print_subthreads_info{
  my ($template, $cid, $cnt, $color, $ref) = @_;
  my $STATE = $template->{'STATE'};
  my $spdb = $template->{'spdb'};
  my $DBH = $spdb->{'dbh'};

  my $sidq =  $DBH->quote($STATE->{'sid'});

  my ($tmp) = 
    $spdb->db_select_many_new(1, "childid", 
			      "ParentAndChild, Posts", 
			      "parentid=$cid AND childid=cid AND sid=$sidq
                          AND approved=1");
  if(!$tmp){
    return $color;
  }
  else{
      while (my ($childid) = $tmp->fetchrow_array){
	  if(!defined($ref)){
	      $template->print_expanded_thread_info($STATE, $childid, $cnt, $color);
	  }
	  else{
	      &{$ref}($STATE, $childid, $cnt, $color);
	  }
	  
	  $color = ($color==0)?1:0;
	  $color = $template->_print_subthreads_info($childid, $cnt+1, $color, $ref);
      }

      $spdb->db_handler_done($tmp);
  }
  return $color;
}

sub _select_children{
  my ($template, $cid, $children) = @_;
  my $spdb = $template->{'spdb'};

  my ($tmp) = $spdb->db_select_many_new(1, "childid", "ParentAndChild", 
					"parentid=$cid");
  if(!$tmp){
    return $children;
  }
  else{
    while (my ($childid) = $tmp->fetchrow_array){
      unshift @$children, $childid;
      $template->_select_children($childid, $children);
    }
    $spdb->db_handler_done($tmp);
  }
}

#########################################################################
# --- two functino ptr
# ---
sub print_expanded_thread_info{
  my ($self, $STATE, $cid, $cnt, $color) = @_;
  my $theme = $template->{'theme'};

  my $mconfig = $template->{'mconfig'};

  my ($display, $page, $view, $postsper, $curr_cid, $mode, $nps);
  ($display, $page, $view, $postsper, $curr_cid, $mode, $nps) = 
    map{ $STATE->{$_} } qw(display page view postsper cid mode nps);  

  my ($subject, $bodytext, $hits, $ip, $time, $closed, $sid, $uid,
      $name, $email, $pid, $lastmod, $replies, $privlev, $hasatt);
  ($subject, $bodytext, $hits, $ip, $time, $closed, $sid, $uid,
   $name, $email, $pid, $lastmod, $replies, $privlev, $hasatt) = 
       $template->_select_comment($cid);

  my ($subject_info, $user_info, $images);

  # --- the poster is anon
  if($uid == 0){
      $user_info = ($name)?"$name(anon)":"anon"; 
      if($email && $name){
	  if($mconfig && $STATE->{'userstatus'} ne "anon"){
	      $user_info = qq|<a href="$mconfig->{'cgidir'}/spmail.cgi?op=newmsg&mto=$email">$user_info</a>|; 
	  }
	  else{
	      $user_info = qq|<a href="mailto:$email">$user_info</a>|; 
	  }
      }
  }
  else{ 
      if(!$privlev){
	  $user_info = qq|<a href="$config->{'cgidir'}/user.cgi?op=userinfo&uid=$uid&page=1&postsper=$postsper">$name</a>|;
      }
      else{
	  $user_info = qq|<b>$name</b>|;
      }
  }

  $subject = $template->filter_html($subject);
  if(length($subject) > $config->{'sublen'}){
    ($subject) = unpack "a$config->{'sublen'}", $subject;
    $subject .= "...";
  }
  if($cid == $curr_cid){ 
    $subject_info = "<B>$subject</B>"; 
  }
  else{
    $sid = $template->url_encode($sid);
    $subject_info = qq|<a href="$config->{'cgidir'}/comments.cgi?op=threadlist&page=$page&sid=$sid&cid=$cid&view=$view&display=$display&mode=$mode#$cid">$subject</a>|;
  }

  unless($cnt){ 

    my ($cnt1, $children, $newpost) = (0, []);

    # --- get the children of this thread
    $template->_select_children($cid, $children);
    
    foreach (@$children){
	my $child = $_;
	$cnt1 += grep { $child eq $_ } split(/\,/, $nps);
    }
    
    if($STATE->{'userstatus'} ne "anon"){    
	$newpost = "<font class=\"caution\">($cnt1 $lang->{'new'})</font>" 
	    if($cnt1);
    }

    # --- if no child
    if(@$children == 0){
	for(my $i=0; $i<1; $i++){
	    $images .= qq|<img src="$theme->{'imagesdir'}/$theme->{'empty_image'}" border="0" alt="*"></img>|;
	}
    }
    else{
	# --- all read
	my $timg;
	if($cnt1){
	    $timg = $theme->{'threadsomeread_image'};
	}
	else{
	    $timg = $theme->{'threadallread_image'};
	}
	$images = qq|<img src="$theme->{'imagesdir'}/$timg" border=0></img>|;
    }
        
    my $timg;
    if($hasatt){
	$timg = $theme->{'threadwattachment_image'};
    }
    elsif($nps =~ /$cid/){ $timg = $theme->{'unreadthread_image'}; }
    else{ $timg = $theme->{'readthread_image'}; }
    $images .= qq|<img src="$theme->{'imagesdir'}/$timg" border=0></img>|; 
  }
  else{
    for(my $i=0; $i<=$cnt; $i++){
      $images .= qq|<img src="$theme->{'imagesdir'}/$theme->{'empty_image'}" border="0" alt="*"></img>|;
    }
    my $timg;
    if($hasatt){
	$timg = $theme->{'threadwattachment_image'};
    }
    elsif($nps =~ /$cid/){ $timg = $theme->{'unreadthread_image'}; }
    else{ $timg = $theme->{'readthread_image'}; }
    $images .= qq|<img src="$theme->{'imagesdir'}/$timg" border=0></img>|;
  }
  if($mode eq "printable"){
        print qq!
	    <tr bgcolor=$theme->{'lhdrcolor'}><td><LI>$subject_info by $user_info on $time</td></tr>
		!;
    }
  else{
      my $bgcolor = ($color==0)?$theme->{'lhdrcolor'}:$theme->{'llhdrcolor'};
      print qq!
	  <TR bgcolor=$bgcolor>
	      <TD>$images&nbsp;$subject_info</TD>
		  <TD WIDTH=$theme->{'cuser_w'}>$user_info</TD>
		      <TD WIDTH=$theme->{'edate_w'}>$time</TD></TR>
			  !;
  }

};

sub print_collapsed_thread{
    shift; print_collapsed_thread_info(@_);
}

sub print_collapsed_thread_info{
  my ($STATE, $cid, $cnt, $color) = @_;
  my $spdb = $template->{'spdb'};
  my $theme = $template->{'theme'};

  my $mconfig = $template->{'mconfig'};

  my ($subject, $bodytext, $hits, $ip, $time, $closed, $sid, $uid,
      $name, $email, $pid, $lastmod, $replies, $privlev, $hasatt) = 
	$template->_select_comment($cid);

  my ($op, $view, $display, $page, $mode, $postsper, $lastlogon, $nps, $mode) = 
    map{ $STATE->{$_} } qw(op view display page mode postsper lastlogon nps mode);

  my ($lastlogonq, $sidq) = map{ $spdb->{'dbh'}->quote($_) } ($lastlogon, $sid);

  my ($subject_info, $user_info, $images);

  # --- user is anon
  if($uid == 0){
      $user_info = ($name)?"$name(anon)":"anon"; 
      if($email && $name){
	  if($mconfig  && $STATE->{'userstatus'} ne "anon"){
	      $user_info = qq|<a href="$mconfig->{'cgidir'}/spmail.cgi?op=newmsg&mto=$email">$user_info</a>|; 
	  }
	  else{
	      $user_info = qq|<a href="mailto:$email">$user_info</a>|; 
	  }
      }  
  }
  else{ 
      if(!$privlev){
	  $user_info = qq|<a href="$config->{'cgidir'}/user.cgi?op=userinfo&uid=$uid&page=1&postsper=$postsper">$name</a>|;
      }
      else{
	  $user_info = qq|<b>$name</b>|;
      }
  }
  
  my $sid1 = $template->url_encode($sid);
  if(length($subject) > $config->{'sublen'}){
    ($subject) = unpack "a$config->{'sublen'}", $subject;
    $subject .= "...";
  }
  $subject_info = qq|<a href="$config->{'cgidir'}/comments.cgi?op=threadlist&page=$page&sid=$sid1&cid=$cid&view=$view&display=$display&mode=$mode#$cid">|.$template->filter_html($subject)."</a>";
    
  my ($cnt1, $children, $newpost) = (0, []);
 
  # --- get the children of this thread
  $template->_select_children($cid, $children);
  
  foreach (@$children){
      my $child = $_;
      $cnt1 += grep { $child eq $_ } split(/\,/, $nps);
  }
  
  if($STATE->{'userstatus'} ne "anon"){
    $newpost = "<b><FONT class=\"caution\">($cnt1 $lang->{'new'})</FONT></B>" 
	if($cnt1);
  }

  # --- if no child
  if(@$children == 0){
      for(my $i=0; $i<1; $i++){
	  $images .= qq|<img src="$theme->{'imagesdir'}/$theme->{'empty_image'}" border="0" alt="*"></img>|;
      }
  }
  else{
      # --- all read
      my $timg;
      if($cnt1){
	  $timg = $theme->{'threadsomeread_image'};
      }
      else{
	  $timg = $theme->{'threadallread_image'};
      }
      $images = qq|<img src="$theme->{'imagesdir'}/$timg" border=0></img>|;
  }

  my $timg;
  if($hasatt){
      $timg = $theme->{'threadwattachment_image'};
  }
  elsif($nps =~ /$cid/){ $timg = $theme->{'unreadthread_image'}; }
  else{ $timg = $theme->{'readthread_image'}; }
  $images .= qq|<img src="$theme->{'imagesdir'}/$timg" border=0></img>|;

  my $replies_field = "&nbsp;";
  $replies_field = "$replies $newpost";

  if($mode eq "printable"){
        print qq!
<tr bgcolor=$theme->{'lhdrcolor'}><td><LI>$subject_info by $user_info on $lastmod ($replies)</td></tr>
  !;
  }
  else{
      my $bgcolor = ($color==0)?$theme->{'lhdrcolor'}:$theme->{'llhdrcolor'};

      print qq!
<TR bgcolor=$bgcolor>
<TD WIDTH=$theme->{'csubject_w'}>$images&nbsp;$subject_info</TD>
<TD WIDTH=$theme->{'cuser_w'}>$user_info</TD>
<TD WIDTH=$theme->{'creplies_w'}>$replies_field</TD>
<TD WIDTH=$theme->{'clastmod_w'}>$lastmod</TD></TR>
  !;
  }
};

return 1;


