# 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::EditCategory;
{
    use strict;
    use Affelio::misc::Debug qw( debug_print);

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


    #######################################################################
    #handler
    #######################################################################
    sub handler{
	my $cgi = shift;
	my $diary = shift;
	my $out_ref = shift;
	
	debug_print("Diary::EditCategory::handler: start.");

	###############################
	#normal show
	###############################
	$out_ref->{tmpl_file}
	= $diary->{afap}->{app__fs_root}."/templates/edit_category.tmpl";
	
	show($diary, $cgi, $out_ref);
	debug_print("Diary::EditCategory::handler: end.");
    }

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

	my $wi = new Affelio::misc::WebInput();
	my $category = $diary->escape($cgi->param("category"));
	my $c_id = $wi->PTN_num($cgi->param("c_id"));
	my $action = $wi->PTN_mode($cgi->param("action"));
	if ($action eq "submit" && $category ne ""){
	    debug_print("Diary::Category::show: insert new category.");
	    # prevent double submit
	    my @same = $diary->getall("SELECT id FROM $diary->{category_table} WHERE category = '$category'");
	    if($#same >= 0) { return; }

	    $diary->{dbh}->do("INSERT INTO $diary->{category_table} VALUES (NULL, '$category')");

	    debug_print("Diary::Category::show: Done, insert category.");
	    $output_ref->{"DONE_ADD"} = '1';
	}elsif($action eq "update" && $category ne "" && $c_id ne ""){
	    $diary->{dbh}->do("UPDATE $diary->{category_table} SET category = '$category' WHERE id = $c_id");
	    $output_ref->{"DONE_UPDATE"} = '1';
	}
	my @categories = $diary->getall("SELECT id, category FROM $diary->{category_table}");
	$output_ref->{"CATEGORIES"}= \@categories;

	debug_print("Diary::EditCategory::show: set output.");

	$output_ref->{"EDIT_CATEGORY"} = '1';
	debug_print("Diary::EditCategory::show end.");
    }

}
1;
