# Path: config/setting.py

# 
# Path: util/login.py
# def login(userid):
#     # 1. sha1(salt+ip+userid+now)
#     now=str(datetime.now())
#     userid=str(userid)
#     hash=sha1(salt+userid+now)
#     # 2. 储存hash id,userid,hash
#     db.insert("login",userid=userid,hash=hash,time=now,discard=0)
#     # 3. write cookie ua:sha1
#     web.setcookie('cu', hash, 3600*24*30)
#     return hash


from config import setting
from util import login
db = setting.db


def check(name,info):
    for key in ["name","avatar",name+"_id",name+"_access_token"]:
        if not info[key]:
            return "no "+key
    return True

def get_by_id(id):
    rows = db.select(["user"],what="avatar,name,id",where="id=$id",vars={"id":id})
    if rows:
        return rows[0]
    else:
        return False

def fav_pages(user_id=None,show_private=False,per=5):
    where = "fav.userid=user.id and fav.pieceid=piece.id and user.id=$user_id"
    if not show_private:
        where += " and private=0"
    pages = db.select(["fav","piece","user"]
        ,what="COUNT(piece.id) as count"
        ,where=where
        ,vars={"user_id":user_id}
    )[0]["count"]
    return pages

def favs_of_page(page=1,per=5,user_id=0,show_private=False):

    sql = """

# Path: config/setting.py

# 
# Path: util/login.py
# def login(userid):
#     # 1. sha1(salt+ip+userid+now)
#     now=str(datetime.now())
#     userid=str(userid)
#     hash=sha1(salt+userid+now)
#     # 2. 储存hash id,userid,hash
#     db.insert("login",userid=userid,hash=hash,time=now,discard=0)
#     # 3. write cookie ua:sha1
#     web.setcookie('cu', hash, 3600*24*30)
#     return hash


# Path: model/user.py
from config import setting
from util import login

db = setting.db


def check(name,info):
    for key in ["name","avatar",name+"_id",name+"_access_token"]:
        if not info[key]:
            return "no "+key
    return True

def get_by_id(id):
    rows = db.select(["user"],what="avatar,name,id",where="id=$id",vars={"id":id})
    if rows:
        return rows[0]
    else:
        return False

def fav_pages(user_id=None,show_private=False,per=5):
    where = "fav.userid=user.id and fav.pieceid=piece.id and user.id=$user_id"
    if not show_private:
        where += " and private=0"
    pages = db.select(["fav","piece","user"]
        ,what="COUNT(piece.id) as count"
        ,where=where
        ,vars={"user_id":user_id}
    )[0]["count"]
    return pages

def favs_of_page(page=1,per=5,user_id=0,show_private=False):

    sql = """

    select piece.id, piece.private, piece.addtime, piece.id, piece.content,piece.pics,