<?php
class TSearch {
	function __construct() {
		include 'db.inc.php';
		$this->db = $db;
	}

	function _getLimit($offset, $show_count) {
		return $offset.','.$show_count;
	}

	function search($word, $offset=0, $show_count=20, $options=array()) {
		return $this->searchLike($word, $offset, $show_count);
	}

	function count($word, $options=array()) {
		return $this->countLike($word);
	}

	function searchLike($word, $offset=0, $show_count=20) {
		if (empty($this->post)) {
			require_once(LIB.'Post.class.php');
			$this->post = new Post();
		}

		$old_id = $this->db->pureSelectOne('posts', 'id', array('limit' => '10000, 1'));
		$w = 'p.content like ?';
		$p = array('%'.str_replace('%', '\\%', $word).'%');
		if ($old_id) {
			$w = 'p.id < ? and '.$w;
			array_unshift($p, $old_id);
		}
		return $this->db->select(
			$this->post->_getFrom(array()),
			$this->post->_getField(array()),
			$w,
			$p,
			array('limit' => $this->_getLimit($offset, $show_count), 'order' => 'p.id desc')
		);
	}

	function countLike($word) {
		if (empty($this->post)) {
			require_once(LIB.'Post.class.php');
			$this->post = new Post();
		}

		$old_id = $this->db->pureSelectOne('posts', 'id', array('limit' => '10000, 1'));
		$w = 'content like ?';
		$p = array('%'.str_replace('%', '\\%', $word).'%');
		if ($old_id) {
			$w = 'id < ? and '.$w;
			array_unshift($p, $old_id);
		}
		return $this->db->count('posts', $w, $p);
	}

	// いらない気がしますけども。
	function searchName($word, $offset=0, $show_count=20) {
		return $this->db->select(
			'posts',
			NULL,
			'display_name like ?',
			array('%'.str_replace('%', '\\%', $word).'%'),
			array('limit' => $this->_getLimit($offset, $show_count), 'order' => 'id desc')
		);
	}

	// no use
	function searchFullIndex($word, $offset=0, $show_count=20) {
		return $this->db->getAll(
			'select * from `'.$this->db->getTableName('posts').'`'
			.' where match(content) against(?) limit '.$this->_getLimit($offset, $show_count),
			array($word)
		);
	}

	function searchSenna($word, $offset=0, $show_count=20) {
		//TODO
	}

	function searchNamazu($word, $offset=0, $show_count=20) {
		//TODO
	}

	function searchGoogle($word, $offset=0, $show_count=20) {
	}
}
