<?php
//@*--

class Theme_Designer_Helper_Data extends Mage_Core_Helper_Abstract
{
    /**
     * @param $themeName
     * @return bool
     */
    public function isActive($themeName) {
        $theme = Mage::getConfig()->getNode('default/design/theme/default');
        return $theme && $theme->asArray() == $themeName;
    }

    /**
     * @param $path
     * @param string $default
     * @return array|string
     */
    public function getConfigValue($path, $default = '') {
        $node = Mage::getConfig()->getNode($path, 'default');
        return $node ? $node->asArray() : $default;
    }

    public function getThemeName()
    {
        $theme = Mage::getConfig()->getNode('default/design/theme/default');
        if ($templateName = Mage::app()->getRequest()->getParam('template', '')) {
            $theme = $templateName;
        }
        return preg_replace('/_preview$/', '', $theme);
    }

    /**
     * @param $block Mage_Core_Block_Abstract
     */
    public function getBlockAttributes($block) {
        $attr = array();
        if (Mage::registry('preview')) {
            $blocks = Mage::registry('designer_blocks');
            $blockName = is_string($block) ? $block : $block->getNameInLayout();
            if (array_key_exists($blockName, $blocks)) {
                $blockIdAttr = array('data-block-id', '"' . $blocks[$blockName]['id'] . '"');
                array_push($attr, $blockIdAttr);
            } else {
                foreach ($blocks as $blockInfo) {
                    if ($blockInfo['position'] === $block) {
                        $blockDataAttr = array('data-position', '"' . $blockInfo['position'] . '"');
                        array_push($attr, $blockDataAttr);
                        break;
                    }
                }
                if (!count($blocks) && in_array($block, $this->getDefaultPositions())) {
                    array_push($attr, array('data-position', '"' . $block . '"'));
                }
            }
        }

        return implode(' ', array_reduce($attr, array($this, '_formatAttributes'), array()));
    }

    /**
     * @param $crumbs
     * @return array
     */
    public function fixPreviewBreadcrumbs($crumbs) {
        $url = Mage::helper('core/url');
        $fixedCrumbs = array();

        foreach ($crumbs as $crumbName => $crumbInfo) {
            $link = $url->removeRequestParam($crumbInfo['link'], 'template');
            $link = $url->removeRequestParam($link, 'preview');
            $link = $url->addRequestParam($link, array(
                'template' => Mage::app()->getRequest()->getParam('template'),
                'preview' => Mage::app()->getRequest()->getParam('preview')
            ));
            $crumbInfo['link'] = $link;
            $fixedCrumbs[$crumbName] = $crumbInfo;
        }

        return $fixedCrumbs;
    }

    /**
     * @return array Default positions
     */
    public function getDefaultPositions() {
        return array('left', 'right');
    }

    /**
     * @param $result
     * @param $item
     * @return mixed
     */
    private function _formatAttributes($result, $item) {
        array_push($result, is_array($item) ? implode('=', $item) : $item);
        return $result;
    }

    /**
     * @return array
     */
    public function getBlocksData() {
        /** @var $blocks Theme_Designer_Model_Resource_Position_Collection */
        $blocks = Mage::getModel('designer/position')->getCollection();
        $blocks->setOrder('`order`', $blocks::SORT_ORDER_ASC);
        $blocks->load();
        $data = array();
        foreach ($blocks as $block) {
            $data[$block->getName()] = array(
                'id' => $block->getId(),
                'position' => $block->getPosition(),
                'order' => $block->getOrder()
            );
        }
        return $data;
    }

    /**
     * @return array
     */
    public function getPositions() {
        /** @var $blocks Theme_Designer_Model_Resource_Position_Collection */
        $positions = array();
        $blocks = Mage::getModel('designer/position')->getCollection();
        $blocks->getSelect()->group(array('position'));
        $blocks->load();
        foreach ($blocks as $block) {
            array_push($positions, $block->getPosition());
        }
        return $positions;
    }

    /**
     * @param string $name Block name
     * @param array $controlData Contains id and template
     * @return string Html output of the block or the block list for the position
     */
    public function getBlockHtml($name, $controlId = null)
    {
        $block = Mage::app()->getLayout()->getBlock($name);
        $output = '';

        if ($block) {
            if (!is_null($controlId)) {
                $block->setControlData($controlId);
            }
            $output = $block->toHtml();
        }

        return $output;
    }

    /**
     * @param $name
     * @param array $blockData
     */
    public function getPositionHtml($name, $blockParams = array())
    {
        $output = '';
        $block = Mage::app()->getLayout()->getBlock($name);
        $positions = Mage::registry('designer_positions');

        if (!$block && $positions && array_search($name, $positions) !== false) {
            // custom designer position
            $blocks = Mage::registry('designer_blocks');
            foreach ($blocks as $blockName => $blockInfo) {
                if ($blockInfo['position'] !== $name) continue;
                $childBlock = Mage::app()->getLayout()->getBlock($blockName);
                if ($childBlock) {
                    $parent = $childBlock->getParentBlock();
                    if ($parent) $parent->unsetChild($blockName);
                    $childBlock->addData($blockParams);
                    $output .= $childBlock->toHtml();
                }
            }
        } else if ($block) {
            if (count($blockParams)) {
                $block->addData($blockParams);
            }
            $output = $block->toHtml();
        }

        return $output;
    }


    /**
     * @param $product
     * @param $control
     * @param null $block
     * @return mixed
     */
    public function renderPrice($product, $control, $block = null) {
        if ($block && get_class($block) === "Mage_Catalog_Block_Product_View") {
            return $block->getTierPriceHtml();
        } else {
            return $this->getPriceHtml($product, true, '', $control);
        }
    }

    public function createTemplate($name, $controlId = null)
    {
        $tpl = new Theme_Designer_Block_Template();
        $tpl->setTemplateType($name);
        if (!is_null($controlId)) {
            $tpl->setControlId($controlId);
        }
        return $tpl;
    }

    public function createSlider($name, $controlId = null)
    {
        $tpl = new Theme_Designer_Block_Catalog_Product_Featured();
        $tpl->setLayout(Mage::app()->getLayout());
        $tpl->setTemplateType($name);
        $tpl->setCategoryId(0);
        if (!is_null($controlId)) {
            $tpl->setControlId($controlId);
        }
        return $tpl;
    }

    public function setTemplateFallback($block)
    {
        $templateType = $block->getTemplateType();
        $controlId = $block->getControlId();
        $filename = $templateType . ($controlId !== null ? '_' . $controlId : '') . '.phtml';

        $params = array( '_type' => 'template', '_default' => false );
        if (Mage::getSingleton('core/design_package')->validateFile('designer/' . $filename, $params)) {
            $block->setTemplate('designer/' . $filename);
        } else if (Mage::getSingleton('core/design_package')->validateFile($filename, $params)) {
            $block->setTemplate($filename);
        } else {
            throw new Mage_Core_Exception('Nonexistent template: ' . $filename);
        }
    }

    /**
     * @param $category
     * @return bool
     */
    public function categoryIsActive($category) {
        $catalogLayer = Mage::getSingleton('catalog/layer');
        if (!$catalogLayer) {
            return false;
        }

        $currentCategory = $catalogLayer->getCurrentCategory();
        if (!$currentCategory) {
            return false;
        }

        $categoryPathIds = explode(',', $currentCategory->getPathInStore());
        return in_array($category->getId(), $categoryPathIds);
    }

    /**
     * @param $input
     * @param $columns
     * @return array
     */
    public function arrayColumns($input, $columns)
    {
        $result = array();
        if (!is_array($columns) || !count($columns)) return $result;
        foreach ($columns as $column) {
            $result[$column] = array();
        }

        foreach ($input as $item) {
            foreach ($columns as $column) {
                $result[$column][] = array_key_exists($column, $item) ? $item[$column] : '';
            }
        }
        return $result;
    }

    /**
     * @param $needle
     * @param $haystack
     * @return bool|int|string
     */
    public function arrayRecursiveSearch($needle, $haystack) {
        foreach($haystack as $key=>$value) {
            $current_key = $key;
            if($needle === $value OR (is_array($value) && $this->arrayRecursiveSearch($needle, $value) !== false)) {
                return $current_key;
            }
        }
        return false;
    }

    /**
     * @param $id
     * @return string
     */
    public function getIdAttribute($id)
    {
        if (Mage::app()->getRequest()->getParam('preview'))
            return 'data-control-id="' . $id . '"';
        return '';
    }
}

//--*@