<?php

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

require_once XOONIPS_CONTROL_PATH.'control_base.php';
require_once XOONIPS_MODEL_PATH.'model_search.php';

class search extends control_base {

  public function init() {
  }
  
  private function mkres(&$ids) {
    $dom = new DOMDocument('1.0');
    $dom->encodeing = 'UTF-8';
    $dom->formatOutput = true;

    $url = "http://xoonips.sourceforge.jp/xoonips/search/";
    $root = $dom->createElementNS($url, 'S:search');
    $search_data = $dom->appendChild($root);
    $root->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:S', $url);
    foreach ($ids as  $value) {
      $root->appendChild($dom->createElementNS($url, 'S:item_id', $value));
    }
    res_code(200, null, true);
    $xml = $this->mk_response_xml(0, -1 , $dom);
    echo $xml;    
  }
  
  public function run($req) {
    $type = $req->get('type');
    $key = $req->get('key');
    if (is_null($key)) {
      $this->rest_notify_err(400, 'Parameter key not specified.');
    }
    $search = new model_search();
    $search->Init();
    $search->set_uid($this->uid);
    // partial result
    $ids = $search->doSearch($type, $key);
    if (count($ids)==0) {
      $this->rest_notify_err(404, 'Not found in item_type_name or key.');
    }else{
      $this->mkres($ids);
    }
  }
}
