<?php

/**
 * Subclass for representing a row from the 'node' table.
 *
 * @package lib.model
 */
class Node extends BaseNode {
    const FIELDS_PAGE_TITLE = 'PageTitle';

    const MENU_TITLE_USE_PAGE_TITLE = 1;
    const MENU_TITLE_CUSTOM = 2;

    const BROWSER_TITLE_IS_PAGE_TITLE = 1;
    const BROWSER_TITLE_CUSTOM = 2;

    const SEO_DESCRIPTION_INHERIT = 1;
    const SEO_DESCRIPTION_CUSTOM = 2;

    const SEO_KEYWORDS_INHERIT = 1;
    const SEO_KEYWORDS_CUSTOM = 2;

    const URL_TYPE_GENERATED = 1;
    const URL_TYPE_CUSTOM = 2;

    const LAYOUT_INHERIT = 1;
    const LAYOUT_CUSTOM = 2;
    const LAYOUT_USE_CURRENT = 3;

    const PERMS_INHERIT = 1;
    const PERMS_ALLOWED_TO_ANYBODY = 2;
    const PERMS_RESTRICTED = 3;

    function setTitle($value, $culture = null)
    {
		$doUpdate = $this->getTitle($culture) != $value;
        parent::setTitle($value, $culture);
        if ($doUpdate && $this->getUrltype($culture) == self::URL_TYPE_GENERATED && !$this->isRoot()) {
            $this->updateUrlIdentifier($culture);
        }
    }

    protected function updateUrlIdentifier($culture = null)
    {
		if(null == $culture){
			$culture = sfConfig::get('app_translations_default_language');
		}
        $trial = $this->normalizeUrlIdentifier($this->getTitle($culture));
        if (empty($trial)) {
            $trial = 'default';
        }
        if ($trial != $this->getUrlIdentifier($culture) && !$this->isRoot()) {
            $ContentTree = ContentTree::instance($culture);
        	$ContentTree->build();
            // foreach($ContentTree->getRoot()->children as $node){
            // printf("%d\n", $node->getId());
            // }
            if ($this->isNew()) {
                $ContentTree->build(true);
                $ContentTreeNode = $ContentTree->getContentTreeNodeById($this->getTreeParent());
                // var_dump($this->getTreeParent());
                // printf(">%d\n", $this->getTreeParent());
            } else {
                $ContentTreeNode = $ContentTree->getContentTreeNodeById($this->getId());
                $ContentTreeNode = $ContentTreeNode->parent;
                // printf(">>%d\n", $this->getId());
            }
            assert($ContentTreeNode);
            if (null != $ContentTreeNode->getChildByUrlIdentifier($trial)) {
                $index = 2;
                do {
                    $trialX = $trial . '-' . $index++;
                } while ((null != $ContentTreeNode->getChildByUrlIdentifier($trialX)));
                $trial = $trialX;
            }

            $this->setUrlIdentifier($trial, $culture);
        }
    }

    public function setUrlType($value, $culture = null)
    {
		$needUpdate = ($value == self::URL_TYPE_GENERATED) && ($this->getUrltype($culture) != $value);
		parent::setUrlType($value, $culture);
		if ($needUpdate) {
			$this->updateUrlIdentifier($culture);
		}
    }

    public function normalizeUrlIdentifier($value)
    {
        return Catalyz::normalizeUrlIdentifier($value);
    }

    function __construct()
    {
        $this->setCurrentLayoutType(self::LAYOUT_INHERIT);
        $this->setUrlProvider(false);
        $this->setPermsType(Node::PERMS_INHERIT);
    }

    /**
     * Return text to use as menu entry for current node
     *
     * @param string $locale
     */
    function getMenuCaption($locale = null)
    {
        switch ($this->getMenuTitleType()) {
            case self::MENU_TITLE_USE_PAGE_TITLE:
                return $this->getTitle($locale);
            case self::MENU_TITLE_CUSTOM:
                return $this->getMenuTitleContent($locale);
            default:
                return false;
        }
    }

    function getPage()
    {
        return Catalyz::getPageByNodeId($this->getId());
    }
    function getSubNavigation($activeNode = null)
    {
        $result = array();
        // xdebug_break();
        if (null == $activeNode) {
            $activeNode = $this;
        }

        foreach($this->getChildren() as $node) {
            if ($node->getIsVisibleInMenu()) {
                $caption = '';
                if (self::MENU_TITLE_USE_PAGE_TITLE == $node->getMenuTitleType()) {
                    $caption = $node->getTitle();
                } elseif (self::MENU_TITLE_CUSTOM == $node->getMenuTitleType()) {
                    $caption = $node->getMenuTitleContent();
                } else {
                    throw new Exception('Invalid MenuTitleType: ' . $node->getMenuTitleType());
                }
                $result[$node->getUrl()] = array(
                    'node' => $node,
                    'caption' => $caption,
                    'active' => $activeNode->isDescendantOf($node) || ($activeNode == $node)
                    );
            }
        }
        return $result;
    }

    function getBrowserTitle()
    {
        switch ($this->getBrowserTitleType()) {
            case self::BROWSER_TITLE_IS_PAGE_TITLE:
                return $this->getTitle();
            case self::BROWSER_TITLE_CUSTOM:
                return $this->getBrowserTitleContent();
            default:
                throw new Exception('Unknown BrowserTitleType: ' . $node->getBrowserTitleType());
        }
        return '';
    }

    function setNodeClass($value)
    {
        $className = 'Node' . $value;
        $instance = new $className();
        $this->setUrlProvider($instance instanceof ICatalyzUrlProvider);
        $this->setOpenTargetProvider($instance instanceof ICatalyzOpenTargetController);
        unset($instance);
        return parent::setNodeClass($value);
    }

    public function getMenuTitle($culture = null)
    {
        switch ($this->getMenuTitleType($culture)) {
            case Node::MENU_TITLE_USE_PAGE_TITLE:
                return $this->getTitle($culture);
            case Node::MENU_TITLE_CUSTOM:
                return $this->getMenuTitleContent($culture);
            default:
                throw new Exception('Unknown MenuTitleType: ' . $this->getMenuTitleType($culture));
        } // switch
    }

    public function getAvailableCultures()
    {
        $result = array();
        $criteria = new Criteria();
        $criteria->add(NodeI18nPeer::ID, $this->getId());
        $nodes = NodeI18nPeer::doSelect($criteria);
        foreach($nodes as $node) {
            $result[] = $node->getCulture();
        }
        return $result;
    }
    public function getAvailableTranslations($force_locale_culture = false)
    {
        $result = array();
        $available_nodes = $this->getAvailableCultures();
		$current_culture = sfConfig::get('app_translations_default_language');
		foreach(Catalyz::GetAllTranslations() as $iso => $name) {
            $languages[$iso] = ucfirst(format_language($iso, $force_locale_culture?$iso:$current_culture));
            if (in_array($iso, $available_nodes)) {
                $result[$iso] = $languages[$iso];
            }
        }

        return $result;
    }

    public function delete($con = null)
    {
        if ($this->hasChildren()) {
            $this->deleteChildren();
            $this->refresh(); // force left/right tree values (updated when deleting children)
        }

        parent::delete($con);
        ContentTree::instance()->clearAllCache();
    }

    public function refresh()
    {
        $criteria = new Criteria();
        $criteria->add(NodePeer::ID, $this->getId());
        $criteria->setLimit(1);
        $rs = NodePeer::doSelectRS($criteria);
        if ($rs->next()) {
            $this->hydrate($rs);
        }
    }

	public function createCopyAsLastChildOfId($node_id){
		$linkedNode = new Node();
		$linkedNode->insertAsLastChildOf(NodePeer::retrieveByPk($node_id, null, false));
		$linkedNode->setIsPublic($this->getIsPublic());
		$linkedNode->setNodeClass($this->getNodeClass());
		$linkedNode->setUrlProvider($this->getUrlProvider());
		$linkedNode->setOpenTargetProvider($this->getOpenTargetProvider());
		$linkedNode->setPermsType($this->getPermsType());
		$linkedNode->setCredentials($this->getCredentials());
		$linkedNode->setIsVisibleInMenu($this->getIsVisibleInMenu());
		$linkedNode->setMenuTitleType($this->getMenuTitleType());
		$linkedNode->setMenuTitleContent($this->getMenuTitleContent());
		$linkedNode->setBrowserTitleType($this->getBrowserTitleType());
		$linkedNode->setBrowserTitleContent($this->getBrowserTitleContent());
		$linkedNode->setSeoKeywordsType($this->getSeoKeywordsType());
		$linkedNode->setSeoKeywordsContent($this->getSeoKeywordsContent());
		$linkedNode->setSeoDescriptionType($this->getSeoDescriptionType());
		$linkedNode->setSeoDescriptionContent($this->getSeoDescriptionContent());
		$linkedNode->setUrltype($this->getUrltype());
		$linkedNode->setUrlIdentifier($this->getUrlIdentifier());
		$linkedNode->setCurrentLayout($this->getCurrentLayout());
		$linkedNode->setCurrentLayoutType($this->getCurrentLayoutType());
		$linkedNode->setTitle($this->getTitle());
		$linkedNode->setSubTitle($this->getSubTitle());
		return $linkedNode;
	}
}
// xfPropelBehavior::register('Node', array('MySearchIndex'));
sfPropelBehavior::add('Node', array(
        'actasnestedset' => array(
            'columns' => array(
                'left' => NodePeer::TREE_LEFT,
                'right' => NodePeer::TREE_RIGHT,
                'parent' => NodePeer::TREE_PARENT,
                'scope' => NodePeer::TREE_ID)
            )
        ));