# Copyright (C) 2006 Affelio Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


package Diary::Top;
{
use strict;
use Affelio::misc::Debug qw( debug_print);

use Exporter;
@Diary::Top::ISA = "Exporter";
@Diary::Top::EXPORT = qw (show handler);


    #######################################################################
    #handler
    #######################################################################
    sub handler{
	my $cgi = shift;
	my $diary = shift;
	my $out_ref = shift;
	
	debug_print("Diary::Top::handler: start.");
	###############################
	#normal show
	###############################
	$out_ref->{tmpl_file}
	= $diary->{afap}->{app__fs_root}."/templates/list_diary.tmpl";
	
	show($diary, $cgi, $out_ref);
	debug_print("Diary::Top::handler: end.");
    }

    #######################################################################
    #show
    #######################################################################    
    sub show{
	my $diary= shift;
	my $cgi=shift;
	my $output_ref = shift;
	debug_print("Diary::Top::show start.");

	my $wi = new Affelio::misc::WebInput();
	my $year = $wi->PTN_num($cgi->url_param("year"));
	my $month = $wi->PTN_num($cgi->url_param("month"));
	my $day = $wi->PTN_num($cgi->url_param("day"));
	my $c_id = $wi->PTN_num($cgi->url_param("c_id"));

	my $edit = 0;
	my $user;
	if($diary->{afap}->check_access("write_diary")) {
	    $user = $diary->{afap}->get_owner_info("nickname");
	    $edit = 1;
	}

	my @entries_param=();
	$output_ref->{"ENTRIES"} = \@entries_param;
	my @entries;

	if($year and $month){
	    @entries = getEntries($diary, $year, $month, $day);
#	    if($day and $#entries == 0) {
#		my ($tid) = @entries;
#		print getURLDescription($diary, $tid->{id});
#	    }
	}
	elsif($c_id){
	    @entries = getEntriesCategory($diary, $c_id);
	}else{
	    debug_print("Diary::Top::show: get newest entries.");
	    @entries = getNewestEntries($diary);
	}
	
	my $i = 0;
	my $category;
	foreach(@entries) {
	    my ($sec, $min, $hour) = localtime($_->{timestamp});
	    
	    if ($_->{c_id} eq ""){
		$category='<AF_M text="none">';
	    }else{
		$category = $diary->getColumn("select category from $diary->{category_table} where id=$_->{c_id}");
	    }

	    my $images="";
	    if (!($_->{contents} =~ s/<image=\"([A-Za-z0-9\-\_]*\.(jpg|png|gif|bmp|jpeg))\">/<a href=\"show_image.cgi\?id=$_->{id}&filename=$1&size=l\"><img src=\"show_image.cgi\?id=$_->{id}&filename=$1&size=s\" border=\"0\"><\/a>/ig)){
		$images=getUploadedImages($diary, $_->{id}, 300, 300);
	    }
	    my $username=$_->{user};
	    
	    push @entries_param,
	    {
		MONTH	=>	$_->{month},
		DAY	=>	$_->{day},
		HOUR	=>	sprintf("%02d", $hour),
		MIN	=>	sprintf("%02d", $min),
		TITLE	=>	$_->{title},
		CATEGORY=>      $category,
		USERNAME=>      $username,
		CONTENTS=>	$_->{contents},
		COMMENT_NO =>	$diary->getCommentsNo($_->{id}),
		TRACKBACKS =>	getTrackbacksNo($diary, $_->{id}),
		ID	=>	$_->{id},
		IMAGES	=>	$images,
		EDITABLE=>	$edit
	    };
	}
	debug_print("Diary::Top::show: set output.");
#$tmpl->param(ENTRIES => \@entries_param, EDITABLE => $edit);
	$output_ref->{"ENTRIES"} = \@entries_param;
	$output_ref->{"EDITABLE"} = $edit;
	$output_ref->{"install_title"} = $diary->{afap}->get_app_info("install_title");
	debug_print("Diary::Top::show end.");
    }



##############################################
# getEntries
#############################################

sub getEntries {
	my $diary  = shift;
	my $year  = $diary->escape(shift, 'int');
	my $month = $diary->escape(shift, 'int');
	my $day   = $diary->escape(shift, 'int');

	my $query = "SELECT * FROM $diary->{entry_table} WHERE year = $year AND month = $month";

	if ($day) {
		$query .= " AND day = $day";
	}

	$query .= " ORDER BY timestamp DESC";

	return $diary->getall($query);
}

##############################################
# getEntriesCategory
#############################################

sub getEntriesCategory {
	my $diary  = shift;
	my $c_id   = shift;
	my $query = "SELECT * FROM $diary->{entry_table} WHERE c_id=$c_id";
	$query .= " ORDER BY timestamp DESC";
	return $diary->getall($query);
}


##############################################
# getNewestEntries
##############################################

sub getNewestEntries {
	my ($diary, $num) = @_;
	unless ($num) { $num = 5; }
	return $diary->getall("SELECT * FROM $diary->{entry_table} ORDER BY timestamp DESC LIMIT $num");
}


##############################################
# getTrackbacksNo
##############################################

sub getTrackbacksNo {
	my $diary = shift;
	my $id   = $diary->escape(shift, 'int');
	return $diary->getColumn("SELECT COUNT(*) FROM $diary->{tb_table} WHERE id = $id");
}

##############################################
# getUploadedImages
##############################################

sub getUploadedImages {
	my ($diary, $id, $width, $height) = @_;

	$width  = "&w=$width" if ($width);
	$height = "&h=$height" if ($height);
	
	my $imgdir = "$diary->{datadir}img/$id/";
	my $ret;
	
	local (*DIR);
	opendir(DIR, $imgdir);
	while (my $file = readdir(DIR)) {
		if (-f $imgdir.$file) {
			$ret .= "<a href=\"show_image.cgi?id=$id&filename=$file\" target=\"_blank\">".
			"<img src=\"show_image.cgi?id=$id&filename=$file$width$height\" border=\"0\" />".
			"</a><br />";
		}
	}
	closedir(DIR);

	return $ret ? "<p>$ret</p>" : "";
}

##############################################
# getURLDescription
##############################################

sub getURLDescription {
	my $diary	= shift;
	my $id		= $diary->escape(shift, 'int');
	
	my ($entry) = $diary->getall("SELECT * FROM $diary->{entry_table} WHERE id = $id");
	my $tmpl = new HTML::Template(filename => "../templates/tpingrdf.tmpl");
	my ($sec, $min, $hour, $mday, $mon, $year) = localtime($entry->{timestamp});
	$year += 1900; $mon += 1;
	
	$tmpl->param(
		TITLE => $entry->{title},
		TURL => "$diary->{afap}->{af}->{site__web_root}/apps/$diary->{afap}->{install_name}/tb/tb.cgi/$id",
		IDENT => "$diary->{afap}->{af}->{site__web_root}/apps/$diary->{afap}->{install_name}/show_diary.cgi?id=$id",
		DESCRIPTION => $entry->{contents},
		CREATOR => $diary->{afap}->{af}->{user__nickname},
		DATE => sprintf("%4d-%02d-%02dT%02d:%02d+09:00", $year, $mon, $mday, $hour, $min),
	);

	return $tmpl->output;
}

}
