#!/usr/bin/perl -w
###########################################
# snip - Ajaxed Text Snippet Storage CGI
# Mike Schilli, 2005 (m@perlmeister.com)
###########################################
use strict;
use CGI;
use CGI::Ajax;
use Cache::FileCache;
use Template;

my $cache = Cache::FileCache->new();

###########################################
sub display {
###########################################
  my($topic) = @_;

  return $cache->get($topic), 
         "Retrieved $topic";
}

###########################################
sub remove_me {
###########################################
  my($topic) = @_;

  $cache->remove($topic);
  return "Deleted $topic";
}

###########################################
sub update_me {
###########################################
  my($topic, $text) = @_;

  $cache->set($topic, $text);

  my $disptext = $text;
  $disptext = substr($text, 0, 60) . 
              "..." if length $text > 60;
  return "Topic '$topic' updated " .
         "with '$disptext'";
}

###########################################
sub show_html {
###########################################
  my $template = Template->new();

  my @keys = sort $cache->get_keys();

  $template->process("snip.tmpl", 
    { topics => \@keys }, 
    \my $result) or die $template->error();

  return $result;
}

###########################################
# main
###########################################
my $cgi = CGI->new();
$cgi->charset("utf-8");

my $pjx = CGI::Ajax->new(
  'display'   => \&display,
  'update_me' => \&update_me,
  'remove_me' => \&remove_me
);
print $pjx->build_html($cgi, \&show_html);
