<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class Chat extends Model
{
    public static $database = 'u1db4';
    
    public static $id;
    
    public static function table($id = null)
    {
        if (is_null($id))
        {
            $id = self::$id;
        }
        return self::$database . '.book_' . $id;
    }

    public static function single($id)
    {
        self::$id = $id;
        return parent::single(__CLASS__);
    }
    
    public function create($data)
    {
        $sql = 'INSERT INTO ' . self::table() . ' SET ';
        $insert[] = self::getEscapeString('createdate', date('Y-m-d H:i:s'));
        unset($data['bookid']);

        foreach ($data as $key => $value)
        {
            $insert[] = self::getEscapeString($key, $value);
        }
        $sql .= implode(',', $insert);
		$this->_db->query($sql);

        BookForum::single()->addSelf(array('income'=>0.1), self::$id);
        
        return $this->_db->getInsertId();
    }
    
    public function delete($id)
    {
        $sql = "DELETE FROM " . self::table() . ' WHERE id = '.$id;
        $this->_db->query($sql);
    }

    public function initialize()
    {
    	$table = self::table(self::$id);
    	$schema = "CREATE TABLE $table (
  `id` bigint(20) NOT NULL auto_increment,
  `bookid` int(10) NOT NULL,
  `uid` int(10) NOT NULL,
  `username` char(16) NOT NULL,
  `message` char(255) NOT NULL,
  `createdate` datetime NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
    	
    	$this->_db->query($schema);
    	
    	$this->_db->update(BookForum::table())->value(array('chat'=>1))->where(array('bookid'=>self::$id))->q();
    	BookForum::single()->refreshCache(self::$id);
    }

    public function getOne($postid)
    {
        $sql = 'SELECT * FROM '.self::table().' WHERE id = '.$postid;
        
        return $this->_db->setQueryString($sql)->find(true);
    }

    public function isCanPost($bookid)
    {
        global $_IORANGE,$cfg_comment,$grouptitle,$iorange_id,$allowpost,$bfchatalternation,$allowbfchat;
        
        if (!$allowbfchat)
        {
            iexit('您目前所在的用户组不允许在聊天室发言');
        }

        if ($allowpost)
        {
            $banned = $this->_db->select()
                  ->from('bookbanned')
                  ->where(array('uid'=>$iorange_id,'bookid'=>$bookid))
                  ->find(true);
            if (!empty($banned))
            {
            	iexit('您已经被本书会管理员禁止在此发言');
            }
        }
        else
        {
        	iexit($grouptitle);
        }

        if ((time() - $_IORANGE['user']['lastcomment']) < $bfchatalternation)
		{
			iexit(ceil($cfg_comment / 60) . '分钟内只能发言一次');
		}
    }
}