<?php

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

require_once XOONIPS_CONTROL_PATH.'control_base.php';

class indexreg extends control_base {

  private $indexBean;

  public function init() {
    $dirname = $trustDirname = 'xoonips';
    $this->indexBean = Xoonips_BeanFactory::getBean('IndexBean', $dirname, $trustDirname);
  }

  /**
   * Path split array.
   * 
   * @param type $indexpath
   * @return type 
   */
  private function getPathArray($indexpath) {
    $explode = explode('/', $indexpath);
    $index_path_arr = array_merge(array_diff($explode, array("")));
    return $index_path_arr;
  }

  /**
   * Public/Private/Group Index Search common sub routine.
   * 
   * @param array $top_arr elminate top
   * @param array $indexes all elemnt fot this index.
   * @param array $index_path_arr indexpath chage array
   * @param array $index
   * @return int 0:not modify,-1:error detect,1:OK
   */
  private function sub_walk_index(&$top_arr, &$indexes, &$index_path_arr, &$index){
    $title = $top_arr['title'];
    if (strcmp($index_path_arr[0],$title) != 0) {
      return -1;
    }
    
    $result = $top_arr;
    array_shift($index_path_arr); // top directory elminate
    $modify_flg = false;
    
    $parent_index_id = $top_arr['index_id'];    
    foreach ($index_path_arr as $path) {
      $child = $this->indexBean->getChilds($indexes, $parent_index_id);
      $find = false;
      foreach ($child as $child_index) {
        $ret = $this->indexBean->getIndex($child_index);
        if (strcmp($ret['title'], $path) == 0) {
          $parent_index_id = $ret['index_id'];
          $find = true;
          break;
        }
      }
      if ($find == false) {
        // Create Child
        $index['uid'] = $this->uid;
        $index['title'] = $path;
        $index['parent_index_id'] = $parent_index_id;
        if ($index['open_level'] == XOONIPS_OL_GROUP_ONLY) {
           $this->indexBean->insertGroupIndex2($index);
           $indexes = $this->indexBean->getGroupIndexes($this->uid);
        } else {
          $this->indexBean->insertIndex($index);
          if($index['open_level'] == XOONIPS_OL_PUBLIC) {
            $indexes = $this->indexBean->getPublicIndexes();
          }else{
            $indexes = $this->indexBean->getPrivateIndexes($this->uid);
          }
        }
        $new_child_ids = $this->indexBean->getChilds($this->indexBean->getChildIndexes($parent_index_id), $parent_index_id);
        $diff = array_diff($new_child_ids, $child);
        $parent_index_id = reset($diff);  // top of array value
        $modify_flg = true;               // modify detect
      }
    }
    if ($modify_flg == false)
      return 0;
    return 1;
  }
  
  public function run($req) {
    // Get params
    $indexpath = $req->get('path');
    $description = $req->get('description');
    if (is_null($indexpath)) {
      $this->rest_notify_err(400, 'Parameter path or description not specified.');
    }

    // Path convert array. After processing covinient way.
    $index_path_arr = $this->getPathArray($indexpath);
    if (count($index_path_arr) <= 1) {
      $this->rest_notify_err(400, 'indexpath too short.');
    }
    $index = array(
      'description' => $description,
    );
    // Public/Private/Group procesing case by case,
    $top_arrs = array();
    if (strcmp($index_path_arr[0], 'Public') == 0) {
      // Public Index
      $top_arr = $this->indexBean->getPublicIndex();
      if (isset($top_arr)) {
        $top_arrs[] = $top_arr;
      }
      $indexes = $this->indexBean->getPublicIndexes();
      $index = array(
        'open_level' => XOONIPS_OL_PUBLIC
      );      
    } else if(strcmp($index_path_arr[0], $this->user) == 0) {
      // Private Index
      // $index_path_arr[0] = $this->user;
      $top_arr = $this->indexBean->getPrivateIndex($this->uid);
      if (isset($top_arr)) {
        $top_arrs[] = $top_arr;
      }
      
      $indexes = $this->indexBean->getPrivateIndexes($this->uid);
      $index = array(
        'open_level' => XOONIPS_OL_PRIVATE
      );
    } else {
      // Group Index
      $top_arrs = $this->indexBean->getGroupIndex($this->uid);
      $indexes = $this->indexBean->getGroupIndexes($this->uid);
      $index = array(
        'open_level' => XOONIPS_OL_GROUP_ONLY
      );      
    }
    if (empty($top_arrs) || empty($indexes)) {
      $this->rest_notify_err(403, 'You don\'t have registering authority.');
    }
    
    $cnt = count($top_arrs);
    $gen_index = 0;
    foreach ($top_arrs as $top_arr) {
      if ($this->indexBean->checkWriteRight($top_arr['index_id'],  $this->uid) == false) {
        if ($cnt == 1) {
          $this->rest_notify_err(403, 'You don\'t have registering authority.');
        } else {
          continue;
        }
      }
      $index['description'] = $description;
      $index['groupid'] = $top_arr['groupid'];
      // Path walk. get index
      $gen_index = $this->sub_walk_index($top_arr, $indexes, $index_path_arr, $index);
      if ($gen_index == -1 && $cnt == 1) {
        $this->rest_notify_err(400, 'indexpath too short.');
      } else if( $gen_index == 0) { 
         // Not Modifyed
        res_code(304);
        exit();
      } else if ($gen_index == 1) {
        break;
      }
    }
    if ($gen_index == -1) {
      $this->rest_notify_err(400, 'indexpath too short or not registed index.');
    }
  }
}
