<?php


class Cmd_search
{
	/**
	 * インスタンスを取得する。
	 */
	static function getinstance()
	{
		return new Cmd_search;
	}
	
	
	function run()
	{
		$get = KinoWiki::getinstance()->getGET();
		if(isset($get['keyword'])){
			$ret = $this->wordsearch();
		}
		else if(isset($get['FromDay'])){
			$ret = $this->timesearch();
		}
		else{
			$ret = $this->showform();
		}
		return $ret;
	}
	
	
	protected function showform()
	{
		$smarty = new CmdSmarty('search');
		$ret['title'] = '検索';
		$ret['body'] = $smarty->fetch('search.tpl.htm');
		return $ret;
	}
	
	
	protected function wordsearch()
	{
		$get = KinoWiki::getinstance()->getGET();
		if(!isset($get['andor']) || !isset($get['type'])){
			throw('パラメータが足りません。');
		}
		
		$_word = mb_split('[\s　]+', $get['keyword']);
		$word = array();
		foreach($_word as $w){
			if($w != ''){
				$word[] = $w;
			}
		}
		if($word == array()){
			return $this->showform();
		}
		
		$wiki = Wiki::getinstance();
		$andsearch = $get['andor'] == 'and';
		switch($get['type']){
			case 'fuzzy':
				$list = $wiki->fuzzysearch($word, $andsearch);
				break;
			case 'ereg':
				$list = $wiki->eregsearch($word, $andsearch);
				break;
			default:
				$list = $wiki->normalsearch($word, $andsearch);
				break;
		}
		
		$smarty = new CmdSmarty('search');
		$smarty->assign('word', join(' ', $word));
		$smarty->assign('type', $get['type']);
		$smarty->assign('list', $list);
		$ret['title'] = '検索結果';
		$ret['body'] = $smarty->fetch('wordsearchresult.tpl.htm');
		return $ret;
	}
	
	
	protected function timesearch()
	{
		$get = KinoWiki::getinstance()->getGET();
		if(!isset($get['FromYear']) || !isset($get['FromMonth']) || !isset($get['FromDay']) || !isset($get['ToYear']) || !isset($get['ToMonth']) || !isset($get['ToDay'])){
			throw('パラメータが足りません。');
		}
		
		$from = mktime(0, 0, 0, $get['FromMonth'], $get['FromDay'], $get['FromYear']);
		$to = mktime(23, 59, 59, $get['ToMonth'], $get['ToDay'], $get['ToYear']);
		
		$wiki = Wiki::getinstance();
		$smarty = new CmdSmarty('search');
		$smarty->assign('fromdate', $from);
		$smarty->assign('todate', $to);
		$smarty->assign('list', $wiki->timesearch($from, $to));
		$ret['title'] = '検索結果';
		$ret['body'] = $smarty->fetch('timesearchresult.tpl.htm');
		return $ret;
	}
	
}
?>