<?php
class search
{
    const TABLE = 'search';
    
    ////////////////////////////////////////////////////////////////////////////
    // Construct and destruct functions.
    
    ////////////////////////////////////////////////////////////////////////////
    // Overload functions.

    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.
    
    public static function save($type, $type_id, $content, $title)
    {
        self::delete($type, $type_id);
        
        db::query()->insert(self::TABLE)
                   ->column('type', $type)
                   ->column('type_id', $type_id)
                   ->column('content', $content)
                   ->column('title', $title)
                   ->execute();
    }
    
    public static function delete($type, $type_id)
    {
        db::query()->delete(self::TABLE)
                   ->where('type', $type)
                   ->where('type_id', $type_id)
                   ->limit(1)
                   ->execute();
    }
    
    public static function get_word_list()
    {
        return db::query()->select(self::TABLE . '_word')
                          ->order('total', 'desc')
                          ->execute();
    }
    
    public static function delete_word($id = null)
    {
        $query = db::query()->delete(self::TABLE . '_word');
        
        if (null !== $id)
        {
            $query->where('id', $id)
                  ->limit(1);
        }
        
        return $query->execute();
    }
    
    public static function get_top_word($limit = 5)
    {
        return db::query()->select(self::TABLE . '_word')
                          ->order('total', 'desc')
                          ->limit($limit)
                          ->execute();
    }
    
    public static function increment($word)
    {
        db::get()->begin();
        
        $result = db::query()->select(self::TABLE . '_word')
                             ->where('word', $word)
                             ->limit(1)
                             ->execute();
        
        $q = db::query();
        
        if (count($result))
        {
            $q->update(self::TABLE . '_word')
              ->column('total', sql::raw('total + 1'))
              ->where('word', $word)
              ->limit(1);
        }
        else
        {
            $q->insert(self::TABLE . '_word')
               ->column('word', $word)
               ->column('total', 1);
        }
        
        $q->execute();
        db::get()->commit();
    }
    
    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
}
