<?php
/*
 *
 * @package		ARI Smart Content
 * @author		ARI Soft
 * @copyright	Copyright (c) 2011 www.ari-soft.com. All rights reserved
 * @license		GNU/GPL (http://www.gnu.org/copyleft/gpl.html)
 * 
 */

(defined('_JEXEC') && defined('ARI_FRAMEWORK_LOADED')) or die;

jimport('joomla.plugin.plugin');

AriKernel::import('Plugin.ContentPlugin');
AriKernel::import('Application.ARISmartContent.Plugin.ParamsPlugin');

define('ARISMARTCONTENT_CONTENTPLG_CONTENT_KEY', '#content#');

class AriSmartContentPluginContent extends JPlugin
{
	var $_pluginTag = '';
	var $_supportNestedTags = false;
	var $_supportDeclParams = true;
	var $_optionsMapping = array();
	var $_typeOptionsMapping = array();
	
	function getTag()
	{
		return $this->_pluginTag;
	}

	function supportNestedTags() 
	{
		return $this->_supportNestedTags;
	}
	
	function execute($content)
	{
		$plg = new AriContentPlugin($this->getTag(), $this->supportNestedTags());
		$handler = array($this, 'contentPluginHandlerInt');
		 
		return $plg->parse($content, $handler);
	}
	
	function contentPluginHandlerInt($params, $content, $sourceContent)
	{
		if ($this->_supportDeclParams)
		{
			$optsPlugin = new AriSmartContentPluginContentParams();
			$declParams = $optsPlugin->getOptions($content);
			
			if (is_array($declParams) && count($declParams) > 0)
			{
				if (!is_array($params))
					$params = array();
					
				$params = array_merge($params, $declParams);
			}
		}

		return $this->contentPluginHandler($params, $content, $sourceContent);
	}
	
	function contentPluginHandler($params, $content, $sourceContent) 
	{	
		return $sourceContent;
	}
	
	function getMergedParams($params)
	{
		$plgParams = !empty($this->params) ? clone($this->params) : new JRegistry();

		foreach ($params as $key => $val)
		{
			$plgKey = $key;
			if (isset($this->_optionsMapping[$key]))
				$plgKey = $this->_optionsMapping[$key];
				
			$plgParams->set($plgKey, $val);
		}
		
		return $plgParams;
	}
	
	function prepareParams($type, $params, $content, $sourceContent)
	{
		$prepareHandler = 'prepareHandler_' . $type;
		
		if (method_exists($this, $prepareHandler))
			$params = $this->$prepareHandler($params, $content, $sourceContent);
		else
			$params = $this->prepareHandler($type, $params, $content, $sourceContent);
		
		return $params;
	}
	
	function prepareHandler($type, $params, $content, $sourceContent)
	{
		$preparedParams = array();

		$paramsMapping = isset($this->_typeOptionsMapping[$type]) ? $this->_typeOptionsMapping[$type] : null;
		if ($paramsMapping && isset($paramsMapping[ARISMARTCONTENT_CONTENTPLG_CONTENT_KEY]) && $content)
			$preparedParams[$paramsMapping[ARISMARTCONTENT_CONTENTPLG_CONTENT_KEY]] = $content;

		if (!is_array($params) || empty($paramsMapping))
			return $preparedParams;

		foreach ($params as $key => $val)
		{
			$resolvedKey = $key;
			if (isset($paramsMapping[$key]))
				$resolvedKey = $paramsMapping[$key];
				
			$preparedParams[$resolvedKey] = $val;
		}
		
		return $preparedParams;
	}
}