#!/usr/bin/perl

BEGIN
{
	unshift (@INC, './modules');
}

use strict;
use warnings;

use CGI::Minimal;
use Template;
use Template::Stash::Context;
use CGI::Carp qw (fatalsToBrowser warningsToBrowser);
use DBI;

use Node;
use Functions;

use Image;
use Goods;

use Data::Dumper;
use CMSConfig;

our $dbh = DBI->connect ($CMSConfig::dataSource, $CMSConfig::userName, $CMSConfig::auth) ||
	die ($DBI::errstr);
$dbh->do ("SET NAMES $CMSConfig::charset");

sub header
{
	print "Content-type: text/html; charset=windows-1251\n\n";
}

header ();

# объект запроса
my $r = CGI::Minimal::new;
# шаблончег
my $t = Template->new ({
	INCLUDE_PATH => 'views',
	STASH => Template::Stash::Context->new (),
#	DEBUG => 'all'
});

my $nodeId = ($r->param ('id'));

my $rootNode = Node::GetRoot ({
	set => [{
		property => 'childs',
		types => ['node'],
		set => [qw (name id block)]
	}]
});

my $node;

if ($nodeId)
{
	$node = Node::GetById ({
		id => $nodeId,
		set => [qw (id name parentId ancestors title showSiblings), {
			property => 'childs',
			types => 'node'
		}]
	});


	$node->set ([{
		property => 'childs',
		types => 'goods',
		set => [qw (id name price), {
			property => 'image',
			set => [qw (fileName url thumbnail)]
		}],
		append => 1
	}, {
		property => 'childs',
		types => 'article',
		append => 1
	}])
		if ($node);

	if ($node->showSiblings)
	{
		my $parent = $node->ancestors->[0];

		$parent->set ({
			property => 'childs',
			types => ['node']
		});
	}
}
else
{
	$node = $rootNode;

	$node->set ({
		property => 'childs',
		types => ['article'],
		append => 1
	});
}


$t->process ('index.tpl', {
	rootNode => $rootNode,
	node => $node
});