# -*- coding=utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import tornado.wsgi
import tornado.options
import os.path,os,datetime,sys,time,codecs
import markdown
import tohtml
import db
import json
import tohtml
import base64
import uuid
def conf():     #全局设定信息
    global NAME,Subtitle,description,keywords,Category,UUID
    conf = db.db("SELECT SITENAME,subtitle,description,keywords,uuid FROM CONFIG")[0]
    NAME = conf[0]
    Subtitle = conf[1]
    description = conf[2]
    keywords = conf[3]
    UUID= conf[4]
    if not UUID:
        UUID=base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes)
        print db.exe("UPDATE config SET uuid='%s' WHERE ID=1" % UUID)
    Category = [(i[0],i[1]) for i in db.db("SELECT ID,Category FROM Category")]
    Category.append((' ',' '))
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
conf()
settings = {
    "static_path" : os.path.join(os.path.dirname(__file__), "./static/"),
    "template_path" : os.path.join(os.path.dirname(__file__), "./templates/"),
    "cookie_secret" : UUID,
    "xsrf_cookies" : True,
    "login_url": "/login"}
class index(tornado.web.RequestHandler):
    def get(self):
        self.redirect('/index.html')
class static(tornado.web.RequestHandler):
    def get(self,url):
        self.write(codecs.open('./html/%s' % url,'r','utf-8').read())
class LoginHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        return self.get_secure_cookie("WLBLOG")

class Manager(LoginHandler):
    @tornado.web.authenticated
    def post(self):
        pass
    @tornado.web.authenticated
    def get(self):
        conf()
        s = db.db("SELECT ID,TITLE,CREATETIME,LEIBIE FROM MY")
        LIST = [(i[0],i[1],i[2],i[3]) for i in s]
        self.render("admin.html",LIST = LIST,title=NAME,tags='tags',NAME=NAME,Category = Category,Subtitle = Subtitle,description=description,keywords=keywords,)
class Edit(LoginHandler):   #文章编辑、新建，类别管理
    @tornado.web.authenticated
    def post(self):
        TYPE=self.get_argument('TYPE','')
        ID=self.get_argument('ID','')
        subject = self.get_argument('subject','')
        tags = self.get_argument('tags','')
        markdown = self.get_argument('markdown','')
        Category = self.get_argument('Category','')
        if TYPE=='DEL':
            Category = Category[0:-1]
            SQL = "DELETE FROM Category WHERE ID IN (%s)" % Category
            self.write(db.exe(SQL))

        elif TYPE=='NEW':
            SQL = "INSERT INTO Category (Category) VALUES ('%s')" % Category
            self.write(db.exe(SQL))
        elif None or "" in (subject,tags,markdown):
            self.write(u"主题、标签、类别及内容均不可为空！")
        else:
            if db.edit(TYPE,subject.encode("utf-8"),tags.encode("utf-8"),markdown.encode("utf-8"),Category.encode("utf-8"),ID):
                tohtml.html().ALL()
                self.write(u'OK，Thanks！')
            else:
                self.write(u'Error!')
    @tornado.web.authenticated
    def get(self):
        conf()
        markdown = tags = subject = LEIBIE = ID = ''
        ID = self.get_argument('id','')
        TYPE = self.get_argument('TYPE','')
        if ID:
            data=db.MARKDOWN(ID)
            subject=data[0]
            markdown=data[2].replace('\'\'','\'').replace('\\\\','\\')
            tags=data[1]
            LEIBIE = data[3]
        else:
            TYPE="ADD"
        self.render("Edit.html",markdown=markdown,
                    subject=subject,
                    tags=tags,
                    title=NAME,
                    NAME=NAME,
                    description=description,
                    keywords=keywords,
                    Category = Category,
                    Subtitle = Subtitle,
                    LEIBIE = LEIBIE,
                    TYPE = TYPE,ID=ID)
class delete(LoginHandler):         #文章删除
    @tornado.web.authenticated
    def get(self):
        ID=self.get_argument('ID','')
        if db.delete(ID):
            tohtml.html().ALL()
            os.remove("./html/%s.html" % ID)
            self.write("0")
        else:
            self.write("数据库异常，刪除失败！")
class update(LoginHandler):         #系统全局设定更新
    @tornado.web.authenticated
    def post(self):
        Result = True
        NAME=self.get_argument('bkname','')
        Subtitle=self.get_argument('subtitle','')
        description=self.get_argument('description','')
        keywords=self.get_argument('keywords','')
        try:
            db.db("update CONFIG SET SITENAME='%s',subtitle='%s',description='%s',keywords='%s' WHERE ID=1 " % (NAME,Subtitle,description,keywords))
        except:
            self.write("ERROR")
        else:
            tohtml.html().ALL()
            self.write("0")
class userupdate(LoginHandler):     #用户管理
    @tornado.web.authenticated
    def post(self):
        user = self.get_secure_cookie("WLBLOG")
        username=self.get_argument('newuser','')
        oldpwd=self.get_argument('oldpwd','')
        pwd1=self.get_argument('pwd1','')
        if db.check(user,oldpwd):
            if not username:
                username=user
            db.db("UPDATE Ver SET PASSWORD='%s',USERNAME='%s' WHERE USERNAME='%s'" % (pwd1,username,user))
            self.write("0")
        else:
            self.write("密码修改失败，请确认你的输入！")
class custom(LoginHandler):     #友情链接、统计代码、多说留言板、文章尾部内容管理
    @tornado.web.authenticated
    def get(self):
        conf()
        try:
            DUOSHUO = db.db("SELECT DUOSHUO FROM Ver")[0][0]
        except:
            DUOSHUO = ''
        NAV = db.db("SELECT ID,NAME,LINK FROM LINK WHERE TYPE='nav'")
        LINK = db.db("SELECT ID,NAME,LINK FROM LINK WHERE TYPE='link'")
        LAST = db.db("SELECT ID,NAME,Remark,HTML FROM Other WHERE LOCATION='last'")
        self.render("custom.html",title=NAME,NAME=NAME,
                    Category = Category,
                    Subtitle = Subtitle,
                    description=description,
                    keywords=keywords,DUOSHUO = DUOSHUO,NAV = NAV,
                    LINK = LINK,LAST = LAST)
    def post(self):
        CMD = self.get_argument('CMD','')
        ID = self.get_argument('ID','')
        name = self.get_argument('name','')
        TYPE = self.get_argument('TYPE','')
        remark = self.get_argument('remark','')
        HTML = self.get_argument('EHTML','')
        LINK = self.get_argument('LINK','')
        if CMD=='DEL':
            if TYPE in ('NAV','LINK'):
                try:
                    db.db("DELETE FROM LINK WHERE ID='%s' " % ID)
                except:
                    pass
            elif TYPE=='LAST':
                try:
                    db.db("DELETE FROM Other WHERE ID='%s' " % ID)
                except:
                    pass
            tohtml.html().ALL()
            self.redirect('/custom')
        elif CMD=='UP':
            if TYPE=="LAST":
                db.db("UPDATE Other SET NAME='%s',HTML='%s',Remark='%s' WHERE ID='%s'" % (name,HTML.replace('\'','\'\'').replace('\\','\\\\'),remark,ID))
            elif TYPE in ('NAV','LINK'):
                db.db("UPDATE LINK SET NAME='%s',LINK='%s' WHERE ID='%s'" % (name,LINK,ID))
            tohtml.html().ALL()
            self.redirect('/custom')
        elif CMD=='NEW':
            if TYPE=="LAST":
                db.db("INSERT INTO  Other (NAME,HTML,Remark,LOCATION,TYPE) VALUES ('%s','%s','%s','%s','belong')" % (name,HTML.replace('\'','\'\'').replace('\\','\\\\'),remark,TYPE.lower()))
            elif TYPE in ('NAV','LINK'):
                db.db("INSERT INTO  LINK (NAME,LINK,TYPE) VALUES ('%s','%s','%s')" % (name,LINK,TYPE.lower()))
            tohtml.html().ALL()
            self.redirect('/custom')
        elif CMD == 'HTML':
            try:
                HTML = db.db("SELECT HTML FROM Other WHERE ID='%s' " % ID)[0][0]
            except:
                pass
            else:
                self.write(HTML.strip().replace('\'\'','\'').replace('\\\\','\\'))
        elif CMD=="DUOSHUO":
            try:
                db.db("UPDATE Ver SET DUOSHUO='%s' WHERE ID='1' " % name)
            except Exception as e:
                self.write("设定失败，原因:%s" % e)
            else:
                tohtml.html().ALL()
                self.write("多说ID已成功设定为：%s" % name)
        elif CMD=="JS":
            if TYPE=='CX':
                try:
                    JSCODE = db.db("SELECT HTML FROM Other WHERE NAME='JSCODE' ")[0][0]
                except:
                    self.write('')
                else:
                    self.write(JSCODE.replace('\'\'','\'').replace('\\\\','\\'))
            elif TYPE=='UP':
                try:
                    db.db("UPDATE Other SET HTML='%s' WHERE NAME='JSCODE'" % HTML.replace('\'','\'\'').replace('\\','\\\\'))
                except Exception as e:
                    self.write(u'修改失败！')
                else:
                    tohtml.html().ALL()
                    self.write(u'修改成功！')

class generate(LoginHandler):
    @tornado.web.authenticated
    def get(self):
        tohtml.html().ALL()
        self.redirect('/')
class upload(LoginHandler):
    @tornado.web.authenticated
    def post(self):
        upload_path=os.path.join(os.path.dirname(__file__),'static/image/')
        file_metas = self.request.files['editormd-image-file']
        filename = ''
        for meta in file_metas:
            filename=time.strftime("%Y%m%d%H%M%S", time.localtime()) + meta['filename']
            filepath=os.path.join(upload_path,filename)
            with open(filepath,'wb') as up:
                up.write(meta['body'])
        print filename
        s = {'success':1,'message': 'OK','url':'static/image/%s' % filename}
        self.write(json.dumps(s))
        
class login(tornado.web.RequestHandler):
    def get(self):
        conf()
        if self.get_secure_cookie("WLBLOG"):
            self.redirect("/admin")
        else:
            self.render("login.html",title=NAME,NAME=NAME,
                        Category = Category,
                        Subtitle = Subtitle,
                        description=description,
                        keywords=keywords,)
    def post(self):
        username = self.get_argument('username','')
        password = self.get_argument('password','')
        if db.check(username,password):
            self.set_secure_cookie("WLBLOG",username)
            self.write("1")
        else:
            self.write("0")
class logout(tornado.web.RequestHandler):
    def get(self):
        self.clear_all_cookies()
        self.redirect("/admin")

App = tornado.wsgi.WSGIApplication([
    (r'/',index),
    (r'/(.*\.html$)',static),
    (r'/admin',Manager),
    (r'/edit',Edit),
    (r'/del',delete),
    (r'/update',update),
    (r'/upload',upload),
    (r'/userupdate',userupdate),
    (r'/custom',custom),
    (r'/generate',generate),
    (r'/login',login),
    (r'/logout',logout)
    ],**settings)
from bae.core.wsgi import WSGIApplication
application = WSGIApplication(App)
