<?php

/**
 * @author Jan Kudlacek
 *
*/

class Themizer
{

var $template;
var $template_path = "blocks/";
var $suffix = ".html";

var $tag_pattern = '!\{\{(\w+)\}\}!';

var $replace_values;

function __construct($theme,$vars = null)
{

	$file_path = $this->template_path.$theme.$this->suffix;

	if(file_exists($file_path))
	{
		$this->template = file_get_contents($file_path);
		
		$this->replace_values = $vars;
	}
	else
		throw new Exception("template file doesn't exists");
}

function isMultipleResult()
{
	return @is_array($this->replace_values[0]);
}

function getResult()
{

$result="";

if($this->isMultipleResult())
{

	$array = $this->replace_values;

foreach($array as $value)
{
	$this->replace_values = $value;

	$result .= preg_replace_callback($this->tag_pattern, array($this,'replace_value'), $this->template);	
}

}
else
$result = preg_replace_callback($this->tag_pattern, array($this,'replace_value'), $this->template);

return $result;
}

function replace_value($matches) {
  if(array_key_exists($matches[1],$this->replace_values))
  return $this->replace_values[$matches[1]];
  else
  return "";
}

function getResultFromArray($keys)
{
	$args = func_get_args();
	
	unset($args[0]);
	$args = array_values($args);
	
	
	$biggest = max($args);
	

	
	$i = 0; $result= array();
	foreach($biggest as $value)
	{
	
		$result[$i] = array();
	
		foreach($keys as $key => $val)
		{
			$result[$i][$val] = $args[$key][$i];
		}		
		$i++;
	} 
	$this->replace_values = $result;
	return $this->getResult();
}


}