<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class Rename extends Model
{
	public static function single($className = __CLASS__)
	{
		if (is_null(self::$_self[$className]))
		{
			self::$_self[$className] = new $className;
		}
		
		return self::$_self[$className];
	}
	
    public static function table()
    {
        return 'ig_renames';
    }

    public function isRename($uid)
    {
        $date = $this->Db()->getValue('SELECT `date` FROM '.self::table().' WHERE uid = '.$uid . ' ORDER BY id DESC LIMIT 1');
        if (empty($date))
        {
            return true;
        }
        $time = strtotime($date);
        if (CTIME - $time > (7 * 24 * 3600))
        {
            return true;
        }
        
        return false;
    }

    public function check($uid, $name)
    {
        $check = $this->Db()->getValue('SELECT COUNT(*) FROM '.Members::table().' WHERE username='.S::sqlEscape($name));
        if ($check)
        {
            return false;
        }
        $check = $this->Db()->getValue('SELECT COUNT(*) FROM '.self::table().' WHERE uid='.S::sqlEscape($uid) . ' AND (old_name='.S::sqlEscape($name).' OR new_name='.S::sqlEscape($name).')');
        if ($check)
        {
            return true;
        }
        $check = $this->Db()->getValue('SELECT COUNT(*) FROM '.self::table().' WHERE (old_name='.S::sqlEscape($name).' OR new_name='.S::sqlEscape($name).')');
        if ($check)
        {
            return false;
        }
        return true;
    }

    public function createLog($uid, $newName, $oldName)
    {
        $this->Db()->insert(self::table())->value(array('uid'=>$uid,'new_name'=>$newName,'old_name' => $oldName, 'date'=>CDATE,'createdate'=>CDATETIME))->q();
        
        return $this->Db()->getInsertId();
    }
}