<?php
class blogMenuManager {

  /**
   * array of child node
   *
   * @var array
   */
  public $tree = array();
  public function __construct($config) {
    foreach ($config as $key=>$value) {

      // Dam bao key la xau ky tu (sua loi key trong)
      if (is_numeric($key)) {
        for ($key = 0; ; $key++) {
          if (!key_exists("user$key", $config)) {
            $key = "user$key";
            break;
          }
        }
      }
      $this->tree[$key] = new blogMenuItem($key, $value);
    }
  }

  public function fromXML($xml) {

  }

  public function getXML() {
    $xml = '<tree id=\'0\'>';
    foreach ($this->tree as $key=>$item) {
      $xml .= $item->getXML();
    }
    $xml .= '</tree>';
    return $xml;
  }


  public function getHTML() {

  }

  public function getJavascriptObject() {
    $obj = '{';
    $isFirst = true;
    foreach ($this->tree as $key=>$item) {
      $obj .= ($isFirst?'':',') . $key . ':' . $item->getJavascriptObject();
      $isFirst = false;
    }
    $obj .= '}';
    return $obj;
  }

  /**
   * Enter description here...
   *
   * @param categoryTreeItem $categoryTreeItem
   */
  public static function buildMenuItemFromCategoryItem($id, $categoryTreeItem) {
    $ret = array(
      'text' => $categoryTreeItem->name,
      'link' => $categoryTreeItem->mod . '/list/cat_id/' . $id
    );
    $child = array();
    if (count($categoryTreeItem->items)>0) {
      foreach ($categoryTreeItem->items as $key=>$item) {
        $child['cat'.$key] = self::buildMenuItemFromCategoryItem($key, $item);
      }
    }

    // Get entry
    $c = new Criteria();
    $c->add(TblblogentryPeer::ENTRY_CATEGORY, $id);
    $c->add(TblblogentryPeer::ENTRY_STATUS, 2, Criteria::LESS_THAN);
    $c->setLimit(30);
    $tblblogentrys = TblblogentryPeer::doSelect($c);
    if (count($tblblogentrys)>0) {
      foreach ($tblblogentrys as $tblblogentry) {
        $child['entry'.$tblblogentry->getEntryId()] = array(
          'text'=>$tblblogentry->getEntryTitle(), ENT_QUOTES,
          'link'=>'entry/show/entry_id/'.$tblblogentry->getEntryId()
        );
      }
    }

    $ret['child'] = $child;
    return $ret;
  }

  /**
   * Build array which describes menu of entry
   *
   */
  public static function buildEntryMenu() {
    $tree = blogStore::$catTree->tree;
    $items = array();
    foreach ($tree as $key=>$item) {
      if ($item->type==2) {
        $items[$key] = $item;
      }
    }

    $menuItems = array();
    foreach ($items as $key=>$item) {
      $menuItems[$key] = self::buildMenuItemFromCategoryItem($key, $item);
    }
    return $menuItems;
  }
}
