""" 一些用于jinja2的模板函数 """
from aiohttp import web
from app.Model.Sysconfig import Sysconfig
from app import dBSession
from app import cache
import time, random

#读取动态配置
def sysconfig(varname):
    sysconfig = cache.get('sysconfig.'+varname)
    res = ''
    if sysconfig == None:
        cache.set('sysconfig.'+varname, None) 
        sysconfig = dBSession.query(Sysconfig).filter_by(varname=varname).first().to_dict()
        cache.set('sysconfig.'+varname,sysconfig)
        res = sysconfig['value']
    else:
        res = sysconfig['value']
    return res

"""
    获取文章详情url
    @param int id 文章ID
    @return string
"""
def getArticleDetailUrl(id=0):
    param = {'id': str(id)}
    if param['id'] != 0:
        url = '/p/'+ param['id']
    else:
        url = '/p/'
    return url

"""
    格式化时间戳
    @param int timestamp
    @param string formart
    @return string
"""
def date(timestamp, formart="%Y-%m-%d %H:%M:%S"):
    date = time.strftime(formart, time.localtime(timestamp))
    return date

"""  
    获取Tag详情url
    @param int id
    @return string
"""
def getTagDetailUrl(id=0):
    url = '/tag/'+str(id)
    return url


"""  
    获取单页详情url
    @param int id 别名
    @return string
"""
def getPageDetailUrl(id=0):
    url = '/page/'+id+'.html'
    return url 


""" 
    随机一个整数
    @param int max 上限
    @return int 
""" 
def randomInt(maxVal):
    value = random.randint(1, maxVal)
    return value

""" 
    推荐
    @params string 站位 
    @retun dict
"""
def tuijian(a=""):
    data =   {
        "0":"不推荐",
        "1":"一级推荐",
        "2":"二级推荐",
        "3":"三级推荐",
        "4":"四级推荐"
    }.items()
    return data

""" 
    后台返回处理模板 
    @param request
    @param msg
    @param code
    @param url
    @param data
    @param wait
    @return response
"""
def backStatus(request, msg, code=1, url='',data='', wait=5):
    if url == '':
        url =  "javascript:history.go(-1);"
    location = str(request.app.router['status'].url_for())+'?msg={}&url={}&data={}&wait={}&code={}'.format(msg, url, data, wait, code)  
    return web.HTTPFound(location)