<?php
//@*--


class Theme_Designer_Model_Observer
{
    /**
     * @param $observer
     */
    public static function controller_action_predispatch(Varien_Event_Observer $observer)
    {
        $action = $observer->getEvent()->getControllerAction();

        if ($action->getRequest()->getParam('template'))
        {
            $template = $action->getRequest()->getParam('template');
            $isPreview = $action->getRequest()->getParam('preview');
            if ($template != '')
            {
                $cfg = Mage::getSingleton('designer/config');
                $appDir = MAGENTO_ROOT . $cfg->get('paths/app_base');

                $baseDirname = $cfg->get('paths/base/dirname');
                $themeDirname = $cfg->get('paths/theme/dirname', array('theme' => $template));
                $loadPriority = array($themeDirname, $baseDirname);
                if ($isPreview) {
                    array_unshift($loadPriority, $cfg->get('paths/preview/dirname', array('theme' => $template)));
                }

                $currentDirname = $themeDirname;

                if (is_readable($appDir . $themeDirname . '/designer/project.json')) {
                    do {
                        $currentDirname = current($loadPriority);

                        if (is_dir($appDir . $currentDirname)
                            && is_readable($appDir . $currentDirname . '/complete')) {
                            break;
                        }
                    } while (next($loadPriority) !== false);
                }

                $actualTheme = basename($currentDirname);

                $package = Mage::getSingleton('core/design_package');
                $package->setTheme('default', $actualTheme);
                $package->setTheme($actualTheme);
                $package->setTheme(null, $actualTheme);

                Mage::register('designer_backup_theme', Mage::getStoreConfig('design/theme/default'));

                Mage::getConfig()->saveConfig('design/theme/default', $actualTheme);
                Mage::getConfig()->reinit();
                Mage::app()->reinitStores();
            }
        }
    }

    /**
     * @param $observer
     */
    public static function controller_action_postdispatch(Varien_Event_Observer $observer)
    {
        $action = $observer->getEvent()->getControllerAction();

        if ($action->getRequest()->getParam('template'))
        {
            $template = $action->getRequest()->getParam('template');
            if ($template != '')
            {
                Mage::getConfig()->saveConfig('design/theme/default', Mage::registry('designer_backup_theme'));
                Mage::getConfig()->reinit();
                Mage::app()->reinitStores();
                Mage::unregister('designer_backup_theme');
            }
        }
    }

    /**
     * @param $observer
     */
    public function controller_action_layout_generate_blocks_before(Varien_Event_Observer $observer)
    {
        $action = $observer->getEvent()->getAction();

        Mage::unregister('preview');
        Mage::unregister('designer_blocks');
        Mage::unregister('designer_positions');

        Mage::register('preview', $action->getRequest()->getParam('preview'));
        Mage::register('designer_blocks', Mage::helper('designer')->getBlocksData());
        Mage::register('designer_positions', Mage::helper('designer')->getPositions());
    }

    /**
     * @param Varien_Event_Observer $observer
     */
    public function cms_page_render(Varien_Event_Observer $observer)
    {
        $action = $observer->getEvent()->getControllerAction();

        $actionName = strtolower($action->getFullActionName());
        $action->getLayout()->getUpdate()->addHandle($actionName . '_after');
    }

    /**
     * @param $observer
     */
    public function core_block_abstract_to_html_before(Varien_Event_Observer $observer)
    {
        /** @var $block Mage_Core_Block_Text_List */
        $block = $observer->getEvent()->getBlock();
        $blockName = $block->getNameInLayout();
        if (in_array($blockName, Mage::helper('designer')->getDefaultPositions())) {
            $this->_checkForNewBlocks($block);
        }
    }

    private function _checkForNewBlocks($block)
    {
        $blockName = $block->getNameInLayout();

        $children = $block->getChild();

        $model = Mage::getModel('designer/position');

        foreach ($children as $child) {
            $childName = $child->getNameInLayout();
            $blocks = Mage::registry('designer_blocks');
            if (!array_key_exists($childName, $blocks)) {
                $lastIndex = count($blocks) - 1;
                $blockList = array_values($blocks);
                $newOrder = isset($blockList[$lastIndex]) && isset($blockList[$lastIndex]['order']) ?
                    $blockList[$lastIndex]['order'] + 1 :
                    0;
                $model->setId(null);
                $model->setName($childName);
                $model->setPosition($blockName);
                $model->setOrder($newOrder);
                $model->save();

                $blocks[$childName] = array(
                    'id' => $model->getId(),
                    'position' => $model->getPosition(),
                    'order' => $model->getOrder()
                );

                Mage::unregister('designer_blocks');
                Mage::register('designer_blocks', $blocks);
            }
        }
    }

}

//--*@