<?php


if (!defined('XOOPS_ROOT_PATH')) exit();

require_once XOONIPS_CONTROL_PATH.'control_base.php';

class indexdel extends control_base {
  
  private $indexBean;
  
  public function init() {
    $dirname = $trustDirname = 'xoonips';
    $this->indexBean = Xoonips_BeanFactory::getBean('IndexBean', $dirname, $trustDirname);
  }
  
  /**
   * children index or item have below index_id
   * 
   * @param type $index_id
   * @return true:have children,flase:no children
   */
  private function has_child($index_id) {
    $cnt_child_ids = count($this->indexBean->getChildIndexes($index_id));
    $cnt_item_ids  = count($this->indexBean->getItemIds(array($index_id)));
    if ($cnt_item_ids > 0 || $cnt_child_ids > 0) {
      return true;
    }
    return FALSE;
  }

  public function run($req) {
    $index_id = $req->get('index_id');
    if (is_null($index_id)) {
      $this->rest_notify_err(400, 'Parameter indexpath not specified.');
    }
    if ($this->indexBean->checkWriteRight($index_id,  $this->uid) == false) {
      $this->rest_notify_err(403, 'Don\'t permit operation.');
    }
    if ($this->has_child($index_id) == false) {
      $indexIds = array($index_id);
      if ($this->indexBean->deleteIndex($indexIds) == false) {
        $this->rest_notify_err(404, 'Index delte fail.');
      }
    } else {
      $this->rest_notify_err(403, 'index_id has child below index or item.');
    }
  }
}
