<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * @category    Artio
 * @package     Artio_MTurbo
 * @copyright   Copyright (c) 2010 Artio (http://www.artio.net)
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

/**
 * The model contains function for preparing configuration data of dynamic transformers.
 *
 * @category    Artio
 * @package     Artio_MTurbo
 * @author      Artio Magento Team (jiri.chmiel@artio.cz)
 * @TODO: radeji udelat jako helper
 */
class Artio_MTurbo_Model_Config_DynamicTransformer extends Varien_Object
{
	
	/**
	 * Internal identifier of AJAX dynamic blocks.
	 * 
	 * @var string
	 */
	const AJAX = 'ajax';
	
	/**
	 * Internal identifiers of ESI dynamic blocks.
	 * 
	 * @var string
	 */
	const ESI  = 'esi';
	
	
	/**
	 * Internal identifiers of disabled dynamic blocks.
	 * 
	 * @var string
	 */
	const DISABLED = 'disabled';
	
	
	/**
	 * Method determines whether block is dynamic or not.
	 * If $block is dynamic method returns true otherwise returns false.
	 * 
	 * If $block is null method returns false.
	 * 
	 * @param Mage_Core_Block_Abstract $block
	 * @return bool
	 */
	public function isBlockDynamic($block)
	{
		return ($block && ($block instanceof Artio_MTurbo_Block_Dynamic));
	}
	
	
	/**
	 * Method determines whether block can be used as dynamic or not.
	 * If $block is set as dynamic method returns true 
	 * else method returns false.
	 * 
	 * If $block is not specified method returns false.
	 * 
	 * @param Mage_Core_Block_Abstract $block
	 * @return bool 
	 */
	public function canBeUsedAsDynamic($block)
	{
		list($handle, $name, $type) = $this->getDynamicInfo($block);
		
		return ($handle && $name && $type && $type != self::DISABLED);
	}
	
	
	/**
	 * Method replace block in the layout. The origin block will
	 * be removed and there will be created new dynamic block.
	 * 
	 * @param Mage_Core_Block_Abstract $block
	 * @param Mage_Core_Model_Layout $layout
	 * @return Artio_MTurbo_Model_Config_DynamicTransformer
	 */
	public function replaceBlockInLayout($block, $layout)
	{
		if (!$block || !$layout || !$this->canBeUsedAsDynamic($block))
			return false;
		
		list($handle, $name, $type) = $this->getDynamicInfo($block);

		
		if ($type == self::ESI)
			$blockType = 'mturbo/esi';
		else if ($type == self::AJAX)
			$blockType = 'mturbo/ajax';
		else
			return false; // unknow block type
		
		$id = $handle.'$'.$name;
		
		$layout->unsetBlock($name);
		$layout->createBlock($blockType, $name, array('identifier' => $id));
		
		return $id;
	}

	
	/**
	 * Get the dynamic name of $block. If $block is configured
	 * as dynamic and it is not disabled then method returns
	 * dynamic blocks info, which is:
	 * 
	 * array(layout handle, layout name, type)
	 * 
	 * If $block is not dynamic or $block is not specified method
	 * returns
	 * 
	 * array("", "", "")
	 * 
	 * @param Mage_Core_Block_Abstract $block
	 * @return array
	 */
	public function getDynamicInfo($block) {

		if (!$block)
			return array("", "", "");
		
		$configBlocks = Mage::getSingleton('mturbo/config')->getDynamicBlocksAsArray();
		
		foreach ($configBlocks as $configBlock)
		{
			$matches = array();
			
			preg_match('/^([^\$#]*)\$([^\$#]*)#([^\$#]*)$/', $configBlock, $matches);
			
			$layoutHandle	= isset($matches[1]) ? $matches[1] : "";
			$layoutName		= isset($matches[2]) ? $matches[2] : "";
			$type			= isset($matches[3]) ? $matches[3] : "";

			if ($layoutName == $block->getNameInLayout())
				return array($layoutHandle, $layoutName, $type);
		}
			
		return array("", "", "");
	}
	
	
	/**
	 * Method transform form data to config and fill it.
	 * 
	 * @param Artio_MTurbo_Model_Config $config
	 * @param array $formData data from form
	 */
	public function extractData($config, $formData = array())
	{
		$helper = Mage::helper('mturbo');
		
		$blocks = isset($formData['blocks']) ? $formData['blocks'] : array();
		
		$names = $blocks['name'];
		$types = $blocks['type'];
		
		$blocksToSave = array();
		
		for ($i=0; $i<count($names); $i++)
		{
			$name = $names[$i];
			$type = $types[$i];
			
			if (array_key_exists($name, $blocksToSave))
				Mage::throwException($helper->__('You cannot choose two blocks with the same type.'));
			
			$blocksToSave[$name] = $name.'#'.$type;
		}
	
		$config->setDynamicBlocks(implode(",", $blocksToSave));
		
		if (isset($formData['cartlink']))
			$config->setDynamicCheckoutCartLink($formData['cartlink']);
	}
	
	
	/**
     * Method transform data for administration form and retrieves as array.
     * 
     * @param Artio_MTurbo_Model_Config $config
     * @return array transformed data
     */
    public function configToForm($config)
    {
    	$userblocks = $config->getDynamicBlocks();
    	$userblocks = explode(',', $userblocks);
    	
    	$blocks = array();
    	
    	foreach ($userblocks as $block)
    	{
    		$parts = explode('#', $block);
    		
    		$name = $parts[0];
    		$type = isset($parts[1]) ? $parts[1] : '';
    		
    		$blocks[] = array('name' => $name, 'type' => $type);
    	}
    	
		return array(
			'userblocks'	=> $blocks,
			'cartlink'		=> $config->getDynamicCheckoutCartLink()
		);
    }
	
}