<?php
//@*--


/**
 * Class Theme_Designer_Block_Template
 */
class Theme_Designer_Block_Template extends Mage_Core_Block_Template
{
    private $_currentSection = '';
    private $_sections = null;

    /**
     * @param string $name
     */
    public function section($name)
    {
        if (is_null($this->_sections)) {
            $this->_sections = array();
            ob_start();
        } else if ($this->_currentSection) {
            $this->_sections[$this->_currentSection] = ob_get_clean();
            ob_start();
        }
        $this->_currentSection = $name;
    }

    public function render($block = null)
    {
        $sections = $this->_getSections();

        $this->setBlockModel($block);

        if (!$this->getControlId()) {
            return join('', $sections);
        } else {
            $this->addData($sections);
            return $this->toHtml();
        }
    }

    /**
     * @return array|mixed
     */
    public function getSections() {
        return array_merge($this->_getSections(), $this->_data);
    }

    /**
     * @return array|null
     */
    private function _getSections() {
        $sections = array();
        if (!is_null($this->_sections)) {
            $sections = $this->_sections;
            $sections[$this->_currentSection] = ob_get_clean();
            $this->_currentSection = '';
            $this->_sections = null;
        }
        return $sections;
    }

    protected function _toHtml()
    {
        if ($blockModel = $this->getBlockModel()) {
            if (substr($this->getTemplateType(), -5) === 'block' && !is_null($blockModel)) {
                $this->setAttributes(Mage::helper('designer')->getBlockAttributes($blockModel));
            }
        }

        Mage::helper('designer')->setTemplateFallback($this);

        return parent::_toHtml();
    }
}

//--*@