<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class BookManageDeputy extends Model
{
    private $_cacheKey = 'BookManageDeputy_';
    
    public static function table()
    {
        return 'ig_bookmanagedeputy';
    }

	public static function single($className = __CLASS__)
	{
		if (!isset(self::$_self[$className]))
		{
			self::$_self[$className] = new $className;
		}

		return self::$_self[$className];
	}

    public function getAll($bookId)
    {
        $sql = 'SELECT uid,expiry FROM '.self::table().' WHERE bookid = '.$bookId.' AND expiry >='.CTIME;
        $result = $this->Db()->setQueryString($sql)->find();

        return $result;
    }

    public function getAllByCache($bookId)
    {
        $key = md5($this->getCacheKey($bookId));
        $result = $this->Cache()->get($key);
        if (false === $result)
        {
            $result = $this->updateAllCache($bookId);
        }

        $deputyArray = array();
        if ('N' != $result)
        {
            foreach ($result as $value)
            {
                if ($value['expiry'] > CTIME)
                {
                    $deputyArray[$value['uid']] = $value;
                }
            }
        }

        return $deputyArray;
    }

    public function updateAllCache($bookId)
    {
        $result = $this->getAll($bookId);
        if (empty($result))
        {
            $result = 'N';
        }
        $this->Cache()->set(md5($this->getCacheKey($bookId)), $result, 6 * 3600);

        return $result;
    }

    public function getCacheKey($bookId)
    {
        return $this->_cacheKey.$bookId;
    }
}