#!/usr/bin/perl -w

use strict;
use CGI;
use Data::Dumper;
use XML::XPath;
use XML::XPath::XMLParser;
use HTML::Template;
use CGI::Carp qw(fatalsToBrowser);
my $q = new CGI;
my %param = $q->Vars;

my $xp = XML::XPath->new(filename => "../recipe/".$param{filename}.".xml");
# my $xp = XML::XPath->new(filename => "/home/cathar/public_html/".$param{filename}.".xml");

my $template = HTML::Template->new(filename => 'base.html', die_on_bad_params => 0);

my $results = $xp->find('/Recipe'); # find all paragraphs

my $context = $results->shift();

my $output;

$output->{TITLE}     = $xp->find('./Title', $context)->string_value();
$output->{COOK_TIME} = $xp->find('./Cooking_Time', $context)->string_value();
$output->{PREP_TIME} = $xp->find('./Preparation_Time', $context)->string_value();
$output->{SERVES}    = $xp->find('./Serves', $context)->string_value();
$output->{COOK}      = $xp->find('./Cook', $context)->string_value();
$output->{PICTURE}   = $xp->find('./Picture', $context)->string_value();

$output->{PICTURE} = "default.gif" if (!$output->{PICTURE});

my $commentsSet = $xp->findnodes('./Comments/comment_item', $context);

while (my $list = $commentsSet->shift()) {
	my %temp = (
	   'comment' => $list->string_value(),
	   'date' => $list->getAttribute("date")
	);
	
	push @{ $output->{COMMENTS} }, \%temp;
}

my $ingrediantsSet = $xp->findnodes('./Ingredients/item', $context);

while (my $list = $ingrediantsSet->shift()) {
	my %temp = (
	   'name' => $list->getAttribute("name"),
	   'amount' => $list->getAttribute("amount"),
	   'measurement' => $list->getAttribute("measurement")
	);

	push @{ $output->{INGREDIANTS} }, \%temp;
}

my $methodSet = $xp->findnodes('./Method/method_item', $context);
while (my $list = $methodSet->shift()) {
	my %temp = (
	   'item' => $list->string_value()
	);

	push @{ $output->{METHOD} }, \%temp;
}

$template->param($output);
print $q->header();
print $template->output();
