package Templates::Admin::TopicsList;

use SmallPigVars qw($config);
use Templates::Admin::SmallPig;
use SPDB;

use CGI qw(:standard :cgi-lib);
use CGI::Cookie ();

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

@ISA = qw(Templates::Admin::OptBlock);

my %CACHE;

sub new{
  my ($class, $space, $spdb, $STATE) = @_;
  my $theme = $STATE->{'theme'};

  $lang = $STATE->{'langptr'};

  my $classvars = {('space' => $space)};
  my $self = Templates::Admin::OptBlock->new($classvars, $theme);
  $self->{'spdb'} = SPDB->new();
  
  my $id = join '', sort values %$self, "topicslist";
  
  return $CACHE{$id} if $CACHE{$id};
  return $CACHE{$id} = bless $self, $class;
}

sub DESTROY{
    my $self = shift;
    my $spdb = $self->{'spdb'};
    $spdb->db_disconnect($spdb->{'dbh'});
}

my $get_collapsed_thread_info = sub{
  my ($STATE, $cid, $cnt) = @_;
  my $theme = $STATE->{'theme'};  
  my ($subject, $bodytext, $hits, $ip, $time, $closed, $sid, $uid,
      $name, $email, $pid, $lastmod, $replies, $privlev) = 
	Templates::Admin::SmallPig::select_comment($cid, $lang);

  my ($op, $view, $display, $page, $mode, $postsper, $lastlogon, $nps, $mode, $mostparent) = 
    map{ $STATE->{$_} } qw(op view display page mode postsper lastlogon nps mode mostparent);
#  $mostparent=1;
  my ($lastlogonq, $sidq) = map{ Templates::Admin::SmallPig::db_quote($_) } ($lastlogon, $sid);

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

  # --- user is anon
  if($uid == 0){
      $user_info = ($name)?"$name(anon)":"anon"; 
      if($email && $name){
	  $user_info = CGI::a({-href=>"mailto:$email"}, $user_info); 
      }  
  }
  else{ 
      if(!$privlev){
	  $user_info = CGI::a({-href=>"$config->{'cgidir'}/user.cgi?op=userinfo&uid=$uid&page=1&postsper=$postsper"}, $name);
      }
      else{
	  $user_info = CGI::a({-href=>"mailto:$email"}, $name);
      }
  }
  
  my $sid1 = Templates::Admin::SmallPig::url_encode($sid);
  if(length($subject) > $config->{'sublen'}){
    ($subject) = unpack "a$config->{'sublen'}", $subject;
    $subject .= "...";
  }
  $subject_info = CGI::a({-href=>"$config->{'cgidir'}/comments.cgi?op=threadlist&page=$page&sid=$sid1&cid=$cid&view=$view&display=$display&mode=$mode"}, Templates::Admin::SmallPig::filter_html($subject));
    
  my ($cnt1, $children, $newpost) = (0, []);
 
  # --- get the children of this thread
 Templates::Admin::SmallPig::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 .= CGI::img({src=>"$theme->{'imagesdir'}/$theme->{'empty_image'}", border=>0});
      }
  }
  else{
      # --- all read
      my $timg;
      if($cnt1){
	  $timg = $theme->{'threadsomeread_image'};
      }
      else{
	  $timg = $theme->{'threadallread_image'};
      }
      $images = CGI::img({src=>"$theme->{'imagesdir'}/$timg", border=>0});
#      $images .= CGI::img({src=>"$theme->{'imagesdir'}/$theme->{'plus_image'}", border=>0});
  }

  my $timg;
  if(Templates::Admin::SmallPig::thread_has_attachment($sid, $cid)){
      $timg = $theme->{'threadwattachment_image'};
  }
  elsif($nps =~ /$cid/){ $timg = $theme->{'unreadthread_image'}; }
  else{ $timg = $theme->{'readthread_image'}; }
  $images .= CGI::img({src=>"$theme->{'imagesdir'}/$timg", border=>0});

  my $select;
  if($op eq "expirethreads" || $op eq "closethreads" ||
     $op eq "openthreads" || $op eq "approvethreads" ||
     $op eq "movecopythreads" || $op eq "umovethreads"){
    $select = CGI::td({-width=>5}, 
["<font size=1><input type=checkbox name=selectedthreads value=\"$cid\"></font>"]);
  }

  my $replies_field = "&nbsp;";
  $replies_field = "$replies $newpost" 
    if($op eq "closethreads" || $op eq "openthreads" || 
       $op eq "topicslist" || $mostparent);

  my $ret;
  if($mode eq "printable"){
        $ret = qq!
<LI>$subject_info by $user_info on $lastmod ($replies)
  !;
  }
  else{
    $ret = qq!
<TR>
$select
<TD WIDTH=53%>$images&nbsp;$subject_info</TD>
<TD WIDTH=16%>$user_info</TD>
<TD WIDTH=13%><FONT SIZE=-1>$replies_field</TD>
<TD WIDTH=16%>$lastmod</TD></TR>
  !;
  }
  
  return $ret;
};

sub get{
  my ($self, $STATE) = @_;
  my $spdb = $self->{'spdb'};
  my $DBH = $spdb->{'dbh'};

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

#  $mostparent = 1;

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

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

  my $theme = $STATE->{'theme'};

  my $from = "Posts AS P";
  my $where = "P.sid=$sid_q ";

  if($mode eq "shownewposts"){
      my $tmp; my $flag=0;
      my @tmp = split(/\, /, $nps->{$sid});
      foreach (@tmp){
	  my ($pid) = Templates::Admin::SmallPig::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 if op is not 
  # --- approvethreads
  if(($op ne "approvethreads" && $op ne "expirethreads" && 
     $op ne "movecopythreads" && $op ne "umovethreads") || $mostparent){
      $from .= ", MostParents AS MP ";
      $where .= "AND MP.cid=P.cid " 
  }
  # --- display all the closed threads if op is openthreads
  $where .= "AND closed=1 " if $op eq "openthreads";
  $where .= "AND closed=0 " if $op eq "closethreads";
  $where .= "AND approved=1 " if($op ne "approvethreads" && 
				 $op ne "expirethreads");
  $where .= "AND approved=0 " if $op eq "approvethreads";
  $where .= "AND uid=$uid " if $op eq "umovethreads";
  
  my $tmp = $sort;
  $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) = $spdb->db_select_many(1, $select, $from, $where, 
				      $others);
  my ($ret, $pageindex) = ("", "");

  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 = Templates::Admin::SmallPig::url_encode("$subject");
    $poster = Templates::Admin::SmallPig::url_encode("$poster");
    $lastpost = Templates::Admin::SmallPig::url_encode("$lastpost");
    $date = Templates::Admin::SmallPig::url_encode("$date");

    my $url;
    $url = "$cgi?op=$op&page=$page&postsper=$postsper&sort=";

    my $str;
    $str = "<A class=bheader HREF=$config->{'basewwwdir'}$url";
    my $end = "&sid=$sid&view=$view";
    
    my $select;
    if($op eq "expirethreads" || $op eq "closethreads" || 
       $op eq "openthreads" || $op eq "approvethreads" || 
       $op eq "movecopythreads" || $op eq "umovethreads"){
      $select = qq!
<TD WIDTH=5 ALIGN=center>
<a class=bheader href="javascript:CheckX()" 
onMouseOver="window.status='Select all displayed messages'; 
return true;" onMouseOut="window.status=' '; return true;">
<b>X</b></a>
</TD>
  !;
    }

    my $replies_field = "&nbsp;";
    $replies_field = $lang->{'replies'}
    if($op eq "closethreads" || $op eq "openthreads" ||
       $op eq "topicslist" || $mostparent);
    $ret .= qq!
<TR BGCOLOR=$theme->{'dhdrcolor'} CELLPADDING=2>
$select
<TD WIDTH=53% CLASS=bheader2>$str$subject$end>$lang->{'subject'}</A></TD>
<TD WIDTH=16% CLASS=bheader2>$str$poster$end>$lang->{'posted_by'}</A></TD>!;
    if(!$view || $view eq "collapsed"){
      $ret .= qq!
<TD WIDTH=13% CLASS=bheader2>$replies_field</TD>
<TD WIDTH=16% CLASS=bheader2>$str$lastpost$end>$lang->{'lastmod'}</A></TD>!;
    }
    else{
      $ret .= qq!
<TD WIDTH=16% CLASS=bheader2>$str$date$end\>$lang->{'date'}</A></TD>!;
    }
    $ret .= qq!</TR>
      !;
  }
  
  if($topics){
    foreach (@$topics){
      my ($sid, $cid, $uid) = @$_;
      if($view eq "collapsed"){
	$ret .= &{$get_collapsed_thread_info}($STATE, $cid);
      }
      elsif($view eq "expanded"){
	$ret .= Templates::Admin::SmallPig::get_thread_info($STATE, $cid, "", $lang);
	Templates::Admin::SmallPig::get_subthreads_info($STATE, $cid, \$ret,
				      \&Templates::Admin::SmallPig::get_thread_info, 
				      1); 
      }
      else{}
    }
  }
  else{
    $ret .= qq!
<TR><TD COLSPAN=4>$lang->{'no_posts'}</TD></TR>
!;
  }

  if($op eq "expirethreads" || $op eq "closethreads" || 
     $op eq "openthreads" || $op eq "approvethreads" ||
     $op eq "movecopythreads" || $op eq "umovethreads"){
    $ret .= qq|
<TR>
<TD>
<font size=1><INPUT NAME=selectedthreads1 TYPE=checkbox onClick="CheckAll();"></font>
</TD>
<TD COLSPAN=4>$lang->{'sel_all_msg'}
</TD>
<TR>
|;
  }
  
  my $totalnums = $spdb->db_count($from, $where);
  # --- create pageindex block 
  # --- if totalnums > 0, create a page index
  if($totalnums > 0){
    use Templates::Admin::PageIndex;
    my $obj = Templates::Admin::PageIndex->new($totalnums, $postsper, $page, 
					       $mode, $theme);
    # --- encode sid
    $sid = Templates::Admin::SmallPig::url_encode($sid);
    # --- encode sort
    $sort = Templates::Admin::SmallPig::url_encode($sort);
    my $url = "&postsper=$postsper&sort=$sort&sid=$sid&view=$view";
    $pageindex .= $obj->get($op, $url);
  }
  
  if($mode ne "printable"){
      $self->{'content'} = $ret;
      $ret = $self->SUPER::get();
      $ret .= $pageindex;
  }

  return ($ret, $totalnums);
}

return 1;
