<?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.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Artio
 * @package     Artio_MTurbo
 * @copyright   Copyright (c) 2009 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

/**
 * 
 *
 * @category   Artio
 * @package    Artio_MTurbo
 * @author     Artio Magento Team <jiri.chmiel@artio.cz>
 */

class Artio_MTurbo_Block_Adminhtml_Edit_Tab_Dynamic
    extends Artio_MTurbo_Block_Adminhtml_Edit_Tab_Abstract
{
	
	/**
	 * The form data values
	 * 
	 * array(
	 * 		'cartlinks'  => single string
	 * 		'userblocks' => array(
	 * 			array('name' => name1, 'type' => type1),
	 * 			array('name' => name2, 'type' => type2),
	 * 			...
	 * 		)
	 * )
	 * 
	 * @var array
	 */
	protected $_formDataValues = array();
	
    /**
     * Constructor.
     */
	public function __construct() {
		parent::__construct();
		$this->setId('dynamic_section');
		$this->_title = $this->getMyHelper()->__('Dynamic loaded blocks');
	}
	
	/**
	 * (non-PHPdoc)
	 * @see Mage_Adminhtml_Block_Widget_Form::_prepareForm()
	 */
    protected function _prepareForm() {
    	
        /* @var $config Artio_MTurbo_Model_Config */
    	$config = Mage::getSingleton('mturbo/config');			
    	
    	$form = new Varien_Data_Form();

    	/* @var $layoutPatch Artio_MTurbo_Model_LayoutPatch */
    	$layoutPatch = Mage::getSingleton('mturbo/layoutPatch');
    	if ($layoutPatch->needToPatch()) {
        	$this->_addLayoutPatchFieldset($form);
    	}
    	 
    	if (!$layoutPatch->needToPatch() || $layoutPatch->isPatched()) {
    	
        	/* fieldset for automatic refresh */
        	$layoutFieldsetDefault = $form->addFieldset('dynamic_block_default', array(
                'legend' => $this->getMyHelper()->__( 'Cart link' ),
                'class'  => 'fieldset'
            ));
            
            $layoutFieldsetDefault->addField('cartlink', 'text', array(
            	'name'		=> 'cartlink',
            	'label'		=> $this->getMyHelper()->__('CSS selector for cart link').':',
            	'after_element_html' => '<span><i>'.$this->getMyHelper()->__("Separate the values by comma ','.").'</i></span>'
            ));
      
    	}
        
        /* bind data */
    	$this->_formDataValues = Mage::getSingleton('mturbo/config_dynamicTransformer')->configToForm($config);
    	
      	$form->setValues($this->_formDataValues);
        $this->setForm($form);
       
        return parent::_prepareForm();
    }
    
	/**
	 * Method adds fieldset for patching layout to form.
	 * @param Varien_Data_Form $form
	 */
    private function _addLayoutPatchFieldset($form) {
    	
        /* @var $patchModel Artio_MTurbo_Model_LayoutPatch */
    	$patchModel = Mage::getSingleton('mturbo/layoutPatch');
    	
    	/* make fieldset */
    	$layoutFieldset = $form->addFieldset('layout_fieldset', array(
            'legend' => $this->getMyHelper()->__('Layout patch'),
            'class'  => 'fieldset'));
    	
    	/* button for patch Mage.php */
        $label = $patchModel->isPatched() ?
        	Mage::helper('mturbo')->__('Remove Layout Patch') :
        	Mage::helper('mturbo')->__('Apply Layout Patch');

        if ($patchModel->isWriteable()) {
        	
        	$layoutFieldset->addType('widget_button', Artio_MTurbo_Helper_Data::FORM_WIDGET_BUTTON);
        	$layoutFieldset->addField('laypatch_button', 'widget_button', array(
        	'name'		=> 'laypatch_button',
        	'label'		=> $label,
        	'style'		=> 'width:800px',
        	'onclick'	=> "setLocation('" . Mage::helper('adminhtml')->getUrl('*/*/layoutpatch') . "')",
        	'comment'	=> $this->getMyHelper()->__('This patch is required for dynamic loaded blocks. (Patched file: app/code/core/Mage/Core/Model/Layout.php)')));
        	
        } else {
        	
        	$layoutFieldset->addType('html_element', Artio_MTurbo_Helper_Data::FORM_HTML);
        	$scriptPath = $patchModel->getLayoutPath();
			$layoutFieldset->addField ( 'layoutstate', 'html_element', 
			array ('label' => '<h4>'.$this->getMyHelper()->__('Layout state').'</h4>',
				   'code' => '<span style="color:red">'.Mage::helper('mturbo')->__("Model '%s' is not writeable. Please change permission to write for patch.", $scriptPath).'</span>'));
		}
        
    	
    }
    
    /**
     * Get HTML of "Add row" button.
     * 
     * @param string $container
     * @param srging $template
     * @param string $title
     * @return string
     */
    public function getAddRowButtonHtml($container, $template, $title='Add')
    {
    	return $this->getLayout()
	    		->createBlock('adminhtml/widget_button')
	    		->setType('button')
	    		->setClass('add')
	    		->setLabel($this->__($title))
	    		->setOnClick("addRow('".$container."', '".$template."')")
	    		->toHtml();
    }
    
    
    /**
     * Get HTML of "Remove row" button.
     */
    public function getRemoveRowButtonHtml($selector='span')
    {
    	return $this->getLayout()
    			->createBlock('adminhtml/widget_button')
    			->setType('button')
    			->setClass('delete')
    			->setLabel($this->__('Remove'))
    			->setOnClick("removeRow(this, '".$selector."')")
    			->toHtml();
    }
    
    
    /**
     * Return block types as array (key => value)
     * 
     * @return array
     */
    public function getBlockTypes()
    {
    	return array(
    		Artio_MTurbo_Model_Config_DynamicTransformer::AJAX => $this->getMyHelper()->__('AJAX'),
    		// Artio_MTurbo_Model_Config_DynamicTransformer::ESI => $this->getMyHelper()->__('ESI'),
    		Artio_MTurbo_Model_Config_DynamicTransformer::DISABLED => $this->getMyHelper()->__('Disabled')
    	);
    }
    
    /**
     * Get layout handles of all XML.
     *
     * @return array
     */
    public function getBlocks()
    {
    	$layout = $this->_getLayoutModel();
    	 
    	$result = array();
    	
    	$designs = $layout->getDesignsAsFlatStrings();
    
    	foreach ($designs as $design)
    	{
    		$layout->setDesign($design);
    		
    		$blocks = $layout->getBlocks();
    		
    		foreach ($blocks as $block)
    		{
    			$handle = isset($block['handle']) ? $block['handle'] : '';
    			$name 	= isset($block['name']) ? $block['name'] : '';
    			$type 	= isset($block['type']) ? $block['type'] : '';
    			
    			if (!$handle || !$name)
    				continue;
    			
    			$key = $handle.'$'.$name;
    			$val = $name.($type ? " ($type)" : "");
    			
    			if (!isset($result[$handle]))
    				$result[$handle] = array();
    			
    			if (!isset($result[$handle][$key]))
    				$result[$handle][$key] = $val;
    		}
    	}
    	
    	// sort blocks in each handle
    	foreach ($result as $h => $b)
    		asort($result[$h]);
    	
    	// sort handles
    	ksort($result);
    	
    	// move default handle at begining of result
    	if (isset($result['default']))
    	{
    		$default = $result['default'];
    		unset($result['default']);
    		$result = array_merge(array('default'=>$default), $result);
    	}
    	
    	return $result;
    }
    
    
    /**
     * Get count of user blocks.
     * 
     * @return number
     */
    public function getFormUserBlockCount()
    {
    	return isset($this->_formDataValues['userblocks']) ? count($this->_formDataValues['userblocks']) : 0;
    }

    
    /**
     * Get user block at index $i. If $i is out of bound
     * method returns null.
     * 
     * @param unknown_type $i
     * @return NULL
     */
    public function getFormUserBlock($i)
    {
    	return isset($this->_formDataValues['userblocks'][$i]) ? $this->_formDataValues['userblocks'][$i] : null;
    }
   
    
    /**
     * Get layout model which provides access to 
     * the layout data (handles, block names etc.)
     * 
     * @return Artio_MTurbo_Model_Layout
     */
    protected function _getLayoutModel()
    {
    	return Mage::getModel('mturbo/layout');
    }

}