# coding=utf-8
import web, settings
import business
from db import db
from datetime import datetime
import requests


url = ('^/api/category/list', 'category_list',
       '^/api/category/(\d+)/add', 'category_add',
       '^/api/category/(\d+)/del', 'category_del',
       '^/api/category/(\d+)/edit', 'category_edit',

       '^/api/content/add', 'content_add',
       '^/api/content/list', 'content_list',
       '^/api/content/(\d+)', 'content_edit',
       '^/api/content/(\d+)/del', 'content_del',
       '^/api/content/(\d+)/test', 'content_test',

       '^/api/testuser/add', 'testuser_add',
       '^/api/testuser/list', 'testuser_list',
       '^/api/testuser/(\d+)/del', 'testuser_del',
       '^/api/testuser/(\d+)/login', 'testuser_login',

       '^/api/fileupload', 'file_upload',
)


#render = web.template.render(settings.TEMPLATE_FOLDER)
web.config.debug = False
render = web.template.render(settings.TEMPLATE_FOLDER, base='layout')
app = web.application(url, globals())
session = web.session.Session(app, web.session.DiskStore('sessions'),initializer={'user':''})

class List(object):
    def GET(self):
        return render.list()

    def POST(self):
        data = web.input()
        db.insert("t_product", name=data.name, description=data.desc)
        return web.seeother('/api/category/list')


class category_add(object):
    def GET(self, parent_id):
        return render.category_add(business.genCategoriesTree(), int(parent_id))

    def POST(self, parent_id):
        data = web.input()
        category_id = db.insert("t_category", name=data.name, parent_id=data.parent_id, description=data.description,
            path='')
        #update the 'path' field
        path = None
        if int(parent_id) == 0:
            path = "$" + str(category_id)
        else:
            parent_category = db.select('t_category', where="id=" + parent_id)
            path = parent_category[0].path + "$" + str(category_id)
        db.update('t_category', where="id = " + str(category_id), path=path)
        return web.seeother('/api/category/list')


class category_del(object):
    def GET(self, category_id):
        category = db.select('t_category', where="id=" + category_id)[0]
        db.delete('t_category', where='path like $path', vars={'path': category.path + "%"})
        return web.seeother('/api/category/list')


class category_edit(object):
    def GET(self, category_id):
        category = db.select('t_category', where="id=" + category_id)[0]
        return render.category_edit(business.genCategoriesTree(), category)

    def POST(self, category_id):
        data = web.input()
        db.update('t_category', where="id = " + category_id, name=data.name, description=data.description)
        return web.seeother('/api/category/list')


class category_list(object):
    def GET(self):
        return render.category_list(business.genCategoriesTree())

###########################################################

class content_add(object):
    def GET(self):
        return render.content_add(business.genCategoriesTree())

    def POST(self):
        data = web.input()
        db.insert('t_content', title=data.title,url=data.url,params=data.params,
            detail=data.detail, category_id=data.category_id,
            insert_date=datetime.now(), update_date=datetime.now())
        return web.seeother('/api/content/list')


class content_list(object):
    def GET(self):
        data = web.input()
        category_id = 0
        page = 1
        if 'category' in data:
            category_id = int(data.category)
        if 'page' in data:
            page = int(data.page)

        item_count = db.query("select count(*) as item_count from t_content where category_id=" + str(category_id))[
                     0].item_count
        page_amount = (item_count + settings.SIZE_OF_PAGE - 1) / settings.SIZE_OF_PAGE
        if page < 0:
            page = 1
        contents = db.select('t_content', where="category_id=" + str(category_id), order='update_date DESC',
            offset=(page - 1) * settings.SIZE_OF_PAGE, limit=settings.SIZE_OF_PAGE)

        return render.content_list(business.genCategoriesTree(), category_id, contents, page, page_amount)


class content_edit(object):
    def GET(self, content_id):
        content = db.select('t_content', where="id=" + content_id)[0]
        return render.content_edit(business.genCategoriesTree(), content)

    def POST(self, content_id):
        data = web.input()
        db.update('t_content', where="id=" + content_id, title=data.title,url=data.url,params=data.params,
            detail=data.detail, category_id=data.category_id, update_date=datetime.now())
        return web.seeother('/api/content/list')

class content_del(object):
    def GET(self, content_id):
        db.delete('t_content', where='id=' + content_id)
        return web.seeother('/api/content/list?category=' + web.input().category)


class content_test(object):
    def GET(self,content_id):
        content = db.select('t_content', where="id=" + content_id)[0]
        user = session.user
        path = business.getCategoryPathById(content.category_id)
        return render.content_test(content,path,user)

    def POST(self,content_id):
        data = web.input()
        user = session.user
        requestSession = requests.session()
        params = {'UserName':user.username,'Password':user.password}
        requestSession.post('https://mail.10086.cn/Login/Login.ashx?_fv=5&cguid=2120107035359',data=params,verify=False)
        response = requestSession.post("http://g2.mail.10086.cn/calendar/List.ashx",data={'pageIndex':'0',
        'curdate':'2013-05-01','actionId':'5','typeId':'0'})


        return response.content

class file_upload(object):
    def POST(self):
        data = web.input(imgFile={})
        filedir = settings.UPLOAD_FILE_PATH
        if 'imgFile' in data:
            filepath = data.imgFile.filename.replace('\\', '/')
            filename = filepath.split('/')[-1]
            fout = open(filedir + '/' + filename, 'wb')#if Unix-Like os,use 'w'
            fout.write(data.imgFile.file.read())
            fout.close()
            return '{"error":0,"url":"/static/upload/' + filename + '"}'
        else:
            return '{"error":1,"message":"请选择上传文件"}'


class testuser_add(object):
    def GET(self):
        return render.testuser_add()
    def POST(self):
        data = web.input()
        db.insert('t_testuser', username=data.username,password=data.password)
        return web.seeother('/api/testuser/list')

class testuser_list(object):
    def GET(self):
        users = db.select('t_testuser')
        return render.testuser_list(users)

class testuser_del(object):
    def GET(self,user_id):
        db.delete('t_testuser', where='id=' + user_id)
        return web.seeother('/api/testuser/list')

class testuser_login(object):
    def GET(self,user_id):
        user = db.select('t_testuser', where='id=' + user_id)[0]
        session.user = user
        return web.seeother('/api/testuser/list')



if __name__ == "__main__":
    app.run()
	
	