<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class BookFloor extends Model
{
    public static $typeMap = array(
        1 => '百楼',
        2 => '千楼',
        3 => '万楼',
    );

    public static $statusMap = array(
        0 => '未发分',
        1 => '已发分',
        2 => '偷袭无效',
    );

	public static function single($className = __CLASS__)
	{
		return parent::single($className);
	}

	public static function table()
	{
		return 'ig_bookfloor';
	}

    public function create($bookId, array $data)
    {
        if (false === ($type = self::checkFloor($data['floor'], $bookId)))
        {
            return false;
        }
        
        $check = $this->Db()->getValue('SELECT COUNT(*) FROM '.BookFloor::table().' WHERE bookid='.$bookId.' AND floor='.$data['floor']);
        if ($check)
        {
            return false;
        }
        
        $table = $this->escape(self::table());
		$sql = "INSERT INTO $table SET ";
        $data['type'] = $type;
        $data['createdate'] = CDATETIME;
        $data['bookid'] = $bookId;
        $data['credits'] = 0;

        $forumInfo = fetchBookForum($bookId);
        if (!empty($forumInfo))
        {
            $floorSet = unserialize($forumInfo['floor']);
            $data['credits'] = BookForum::single()->isMember($bookId, $data['uid']) ? $floorSet[1][$type] : $floorSet[2][$type];
            if ($data['credits'] > $forumInfo['income'])
            {
                $data['credits'] = $forumInfo['income'];
            }
            BookForum::single()->decrement(array('income'=>$data['credits']), $bookId);
        }
        
        $insert[] = self::getEscapeString('date', CDATE);
        foreach ($data as $key => $value)
		{
			$insert[] = self::getEscapeString($key, $value);
		}

        $sql .= implode(',', $insert);
		$this->Db()->query($sql);
        
		return $this->Db()->getInsertId();
    }

    public static function checkFloor($floor)
    {
        switch ($floor)
        {
            case 0 == $floor % 10000:
                return 3;
            case 0 == $floor % 1000:
                return 2;
            case 0 == $floor % 100:
                return 1;
            default:
                return false;
        }
    }
}