<?php

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

require_once XOONIPS_CONTROL_PATH.'control_base.php';

class indexmove extends control_base {

  private $indexBean;

  public function init() {
    $dirname = $trustDirname = 'xoonips';
    $this->indexBean = Xoonips_BeanFactory::getBean('IndexBean', $dirname, $trustDirname);
  }
  
  private function exist_index_id($index_id) {
    if ( $this->indexBean->getIndex($index_id) === false) {
      return false;
    }
    return true;
  }
  
  /**
   * Among Public , Private and Group Index don't move
   * 
   * @param type $index_id
   * @param type $parent_index_id
   * @return type 
   */
  private function comp_index_species($index_id, $parent_index_id) {
    $index_id_arr = $this->indexBean->getIndex($index_id);
    $parent_index_id_arr = $this->indexBean->getIndex($parent_index_id);
    return $index_id_arr['open_level'] == $parent_index_id_arr['open_level'];
  }

  /**
   * Belonging to same group?
   * 
   * @param type $index_id
   * @param type $parent_index_id
   */
  
  private function is_same_group($index_id, $parent_index_id) {
    $parent_index = $this->indexBean->getIndex($parent_index_id);
    $index = $this->indexBean->getIndex($index_id);
    
    if ($parent_index['open_level'] == XOONIPS_OL_GROUP_ONLY && 
        $index['open_level'] == XOONIPS_OL_GROUP_ONLY &&
        $parent_index['groupid'] != $index['groupid']) {
      $this->rest_notify_err(403, 'parent_index_id and index_id don\'t belong to same group.');
    }
  }

  public function run($req) {
    $index_id = $req->get('index_id');
    $parent_index_id = $req->get('parent_index_id');
    if (is_null($index_id) || is_null($parent_index_id)) {
      $this->rest_notify_err(400, 'Parameter index_id or parent_index_id not specified.');
    }
    
    // Parent Index owned this user?
    if ($this->indexBean->checkWriteRight($parent_index_id, $this->uid) == false) {
      $this->rest_notify_err(400, 'parent_index_id doesn\'t permit access index.');
    }
    if ($this->indexBean->checkWriteRight($index_id, $this->uid)) {
      if ($this->exist_index_id($parent_index_id) == false) {
        $this->rest_notify_err(400, 'parent_index_id does not exist.');
      }
      if ($this->comp_index_species($index_id, $parent_index_id) == false) {
        $this->rest_notify_err(403, 'parent_index_id and index_id aren\'t same species.');
      }
      $this->is_same_group($index_id, $parent_index_id);
      $rc = $this->indexBean->moveto($index_id, $parent_index_id);
      if ($rc == false) {
        $this->rest_notify_err(404, 'Index cannot move.');
      }
    } else {
      $this->rest_notify_err(403, 'Don\'t permit operation.');
    }
  }
}
