<?php

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

require_once XOONIPS_CONTROL_PATH.'control_base.php';

/*
 * XML does not treate in this class.
 * Therfore , Methods implement here.
 */
class indexupdate extends control_base {
  
  private $indexBean;
  
  public function init() {
    $dirname = $trustDirname = 'xoonips';
    $this->indexBean = Xoonips_BeanFactory::getBean('IndexBean', $dirname, $trustDirname);
  }

  private function get_index($index_id) {
    $index = $this->indexBean->getIndex($index_id);
    if (empty ($index)) {
      return array();
    }
    return array(
      'title' => $index['title'],
      'index_id' => $index['index_id'],
      'description' => $index['description']
    );
  }

  private function index_update($index) {
    return $this->indexBean->updateIndex($index);
  }
  
  /**
   * Main Interface
   * You must call this method using Indexupdate.
   * 
   * @param object $req POST object.
   */
  public function run($req) {
    $title = $req->get('title');
    $index_id = $req->get('index_id');
    $description = $req->get('description');
    if (!isset($index_id) || (is_null($title) && is_null($description))) {
      $this->rest_notify_err(400, 'Parameter index_id, description or title not specified.');
    }
    $index = $this->get_index($index_id);
    if (empty($index)) {
      $this->rest_notify_err(404, 'index_id illegal');
    }
    
    if (is_null($title) == false) {
      $index['title'] = $title;
    }
    if (is_null($description) == false) {
      $index['description'] = $description;
    }

    if ($this->indexBean->checkWriteRight($index_id, $this->uid)) {
      $rc = $this->index_update($index);
      if ($rc == false) {
        $this->rest_notify_err(404, 'Index update fail.');
      }
    } else {
      $this->rest_notify_err(403, 'Don\'t permit operation.');
    }
  }
}
