#-*- coding:utf-8 -*-
from flask import g, render_template, request, url_for, redirect, session

from chartnet import app
from chartnet import setting
from models import operatorDB
from common import login_required
from werkzeug import secure_filename
import os
import re
import time
from PIL import Image
from StringIO import StringIO
import sae
from sae.storage import Bucket
import logging
import json

#jinja filter
from datetime import datetime

@app.template_filter()
def timesince(timestamp, default=u"刚才"):
    """
    Returns string representing "time since" e.g.
    3 days ago, 5 hours ago etc.
    """
    dt = datetime.fromtimestamp(timestamp)
    now = datetime.now()
    diff = now - dt
    
    periods = (
        (diff.days / 365, u"年"),
        (diff.days / 30, u"月"),
        (diff.days / 7, u"星期"),
        (diff.days, u"天"),
        (diff.seconds / 3600, u"小时"),
        (diff.seconds / 60, u"分钟"),
        (diff.seconds, u"秒钟"),
    )

    for period, singular in periods:
        if period:
            return u"%d %s之前" % (period, singular)

    return default

@app.template_filter()
def tag_separate_link(tags):
    """
    return string of seperated tag links
    """
    links = ''
    if tags:
        taglist = tags.split(',')
        for tag in taglist:
            links += "<a href='/tag/%s' rel='tag'>%s</a> &nbsp;"%(tag, tag)
    return links

from sae.ext.storage import monkey
monkey.patch_all()

# create db table if first run
from chartnet import db
db.create_all(app=app)

if True:
    import sae.mail
    from sae.taskqueue import add_task
    import sae.storage


######
def put_obj2storage(file_name = '', data = '', expires='365', type=None, encoding= None, domain_name = setting.STORAGE_DOMAIN_NAME):
    import sae.const  
    access_key = sae.const.ACCESS_KEY  
    secret_key = sae.const.SECRET_KEY  
    appname = sae.const.APP_NAME  
    domain_name = "attachment" 
    bucket = Bucket(domain_name)
    bucket.put()
    bucket.post(metadata={'expires': '2d'})
    attrs = bucket.stat()
    bucket.put_object(file_name, data)
    file_url = bucket.generate_url(file_name)
    #begin to created
    im = Image.open("/s/attachment/" + file_name)
    #im = Image.open(bucket.get_object_contents(file_name))
    im.thumbnail((320,200))
    #im.save("/s/attachment/" + file_name+"_thumbnail.jpg")
    imgext = re.search("(\.\w*)$", file_name)
    if imgext:
        thumbnail_name = file_name + "_thumbnail"+ imgext.group(1)
    else:                
        thumbnail_name = file_name + "_thumbnail.jpg"
    pureext = imgext.group(1)[1:]
    if pureext == "jpg":
        pureext = "jpeg"
    #bucket.put_object(thumbnail_name, im.tostring('jpeg', 'RGB'))
    bucket.put_object(thumbnail_name, im.tostring("jpeg", 'RGB'))
    thumbnail_url = bucket.generate_url(thumbnail_name)
    #s = sae.storage.Client()
    #ob = sae.storage.Object(data = data, cache_control='access plus %s day' % expires, content_type= type, content_encoding= encoding)
    return file_url, thumbnail_url
    #return s.put(domain_name, file_name, ob)
#from sae.const import (MYSQL_HOST, MYSQL_HOST_S,MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB)

@app.before_request
def before_request():
	#appinfo = sae.core.Application()
	#g.db = MySQLdb.connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS,MYSQL_DB, port=int(MYSQL_PORT)
	pass

@app.teardown_request
def teardown_request(exception):
	if hasattr(g,'db') : g.db.close()

@app.route('/start')    
def start():
    return render_template('start.html')

@app.route('/crossdomain.xml')
def crossdomain():
    return render_template('crossdomain.xml')


@app.route('/')
@app.route('/index', methods = ['GET', 'POST'])
@app.route('/index/<int:page>', methods = ['GET', 'POST'])
def _index(page = 1):
    posts = None
    if request.args.get('_start','') != '' :
        _start = int(request.args.get('_start', ''))
    if request.args.get('cat','') != '' :
        posts = operatorDB.get_post_page_category(request.args.get('cat',''))
    elif request.args.get('tags','') != '' :
        posts = operatorDB.get_post_page_tags(request.args.get('tags',''))
    else:
        posts = operatorDB.get_post_page(page)
    editor_posts = operatorDB.get_editor_post(0,3)
    return render_template('index.html', c=request.args.get('cat',''),
                           t=request.args.get('tags',''),
                           tags = operatorDB.get_all_tag_name(),
                           cats=operatorDB.get_all_cat_name(),
                           links=operatorDB.get_all_links(),
                           posts=posts,
                           BASE_URL=setting.BASE_URL,
                           editor_posts = editor_posts)


@app.route('/category/<string:category_name>')
def category(category_name):
    _start = 0
    _end = 0
    if request.args.get('_start', '') != '':
        _start = int(request.args.get('_start', ''))
    _end = _start + setting.EACH_PAGE_POST_NUM
    posts = operatorDB.get_post_page_category(
                            category_name)
    return render_template('category.html',
                           cats = operatorDB.get_all_cat_name(),
                           posts = posts,
                           BASE_URL = setting.BASE_URL,
                           category_name = category_name)

@app.route('/tag/<string:tag_name>')
def tag(tag_name):
    _start = 0
    _end = 0
    if request.args.get('_start', '') != '':
        _start = int(request.args.get('_start', ''))
    _end = _start + setting.EACH_PAGE_POST_NUM
    posts = operatorDB.get_post_page_tags(
                            tag_name)
    logging.error(">>post %s"% len(posts))
    return render_template('tag.html',
                           tags = operatorDB.get_all_tag_name(),
                           posts = posts,
                           BASE_URL = setting.BASE_URL,
                           tag_name = tag_name)

@app.route('/download')
def download():
	return render_template('download.html',coms=operatorDB.get_comments_new(),tags = operatorDB.get_all_tag_name(),cats=operatorDB.get_all_cat_name(),links=operatorDB.get_all_links())

@app.route('/detailpost/<int:post_id>', methods=['GET', 'POST'])
def detailpost(post_id):
	if request.method == 'POST':
		operatorDB.add_new_comment(post_id,request.form.get('author', ''),request.form.get('email', ''),request.form.get('url', ''),1,request.form.get('comment', ''))
	_article = operatorDB.detail_post_by_id(post_id)
	comments = operatorDB.get_post_comments(post_id)
	comLen = len(comments)
	_older,_newer = operatorDB.get_post_older_newer(post_id)
	return render_template('detailpost.html',_older=_older,_newer=_newer,coms=operatorDB.get_comments_new(),tags = operatorDB.get_all_tag_name(),cats=operatorDB.get_all_cat_name(),links=operatorDB.get_all_links(),post_id=post_id,comLen=comLen,comments=comments,obj=_article,add_time=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(_article._add_time)))

@app.route('/timeline')
def _timeline():
	_data = operatorDB.getTimelineData()
	rs = u'{"timeline":{"headline":"c-house的时间线","type":"default","text":"始于2012年7月","date": [%s]}}' % _data.timeline_data
	return render_template('timeline.html',rs=rs,coms=operatorDB.get_comments_new(),tags = operatorDB.get_all_tag_name(),cats=operatorDB.get_all_cat_name(),links=operatorDB.get_all_links())

@app.route('/about', methods=['GET', 'POST'])
def _about():
    post = operatorDB.getAboutPost()
    return render_template('about.html', post=post)

@app.route('/contact-us', methods=['GET', 'POST'])
def _contact():
    post = operatorDB.getContactPost()
    return render_template('contact.html', post=post)

@app.route('/soGoodorBad')
def _soGoodorBad():
	if request.args['action']=='so_good':
		operatorDB.addSogood(request.args['id'])
	if request.args['action']=='so_bad':
		operatorDB.addSobad(request.args['id'])
	return redirect(url_for('_about'))

#管理员
@app.route('/admin/index')
@login_required
def admin_index():
	return render_template('admin/index_admin.html',title=u'后台管理',SITE_TITLE=setting.SITE_TITLE,BASE_URL=setting.BASE_URL)

@app.route('/admin/logout')
def admin_logout():
	session.pop('username', None)
	return render_template('admin/login_admin.html',has_user=operatorDB.has_user(),title=u'管理员登录',SITE_TITLE=setting.SITE_TITLE,BASE_URL=setting.BASE_URL)

@app.route('/admin/login', methods=['GET', 'POST'])
def admin_login():
	if request.method == 'POST':
		if not operatorDB.has_user():
			operatorDB.add_user(request.form.get('name', ''),request.form.get('password', ''))
			session['username'] = request.form.get('name', '')
			return redirect(url_for('admin_index'))
		if operatorDB.login_user(request.form.get('name', ''),request.form.get('password', '')):			 
			session['username'] = request.form.get('name', '')
			return redirect(url_for('admin_index'))
	return render_template('admin/login_admin.html',has_user=operatorDB.has_user(),title=u'管理员登录',SITE_TITLE=setting.SITE_TITLE,BASE_URL=setting.BASE_URL)

@app.route('/admin/links', methods=['GET', 'POST'])
@login_required
def admin_links():
	obj = None
	if request.method == 'POST':
		act = request.form['act']
		if act == 'add':
			operatorDB.add_new_link(request.form.get('name', ''),request.form.get('sort', ''),request.form.get('url', ''))
		if act == 'edit':
			operatorDB.update_link_edit(request.form.get('id', ''),request.form.get('name', ''),request.form.get('sort', ''),request.form.get('url', ''))
	if request.method == 'GET':
		act = request.args.get('act', '')
		if act == 'del': 
			operatorDB.del_link_by_id(request.args.get('id', ''))
		if act == 'edit':
			obj = operatorDB.get_link_by_id(request.args.get('id', ''))
	return render_template('admin/link_admin.html',obj=obj,objs=operatorDB.get_all_links(),title=u'友情链接管理',SITE_TITLE=setting.SITE_TITLE,BASE_URL=setting.BASE_URL)

@app.route('/admin/add_post', methods=['GET', 'POST'])
@login_required
def admin_addpost():
    if request.method == 'POST':
        _post_type = request.form.get('post_type', '')
        if _post_type == '':
            _post_type = 0
        _tags = request.form.get('tags', '').replace(u'，',',')
        tagslist = set([x.strip() for x in _tags.split(',')])
        try:
            tagslist.remove('')
        except:
            pass
        if tagslist:
            _tags = ','.join(tagslist)
        logging.error(request.form.get('content', ''))
        imgsrc = re.search("img src=(\S*)", request.form.get('content', ''))
        imgthumbnail = ''
        if imgsrc:
            imgext = re.search("(\.\w*)$", imgsrc.group(1))
            if imgext:
                logging.error(">>admin_addpost: %s" % imgsrc.group(1)+"_thumbnail"+ imgext.group(1))
                imgthumbnail = imgsrc.group(1)+"_thumbnail"+ imgext.group(1)
        _article = operatorDB.add_new_article(request.form.get('category', ''),
                                              request.form.get('title', ''),
                                              request.form.get('content', ''),
                                              _tags,request.form.get('password', ''),
                                              shorten_content(request.form.get('content', '')),
                                              imgthumbnail, _post_type,
                                              request.form.get('editor_title', '')
                                              )
        
        postId = _article._id

        if _tags!='':
            operatorDB.add_postid_to_tags(_tags.split(','), str(postId))
        operatorDB.add_postid_to_cat(request.form.get('category', ''),str(postId))
        if operatorDB.isHasData():
            updateTimelineData(_article)
        else:
            addTimelineData()
    cats = operatorDB.get_all_cat_name()
    tags = operatorDB.get_all_tag_name()
    return render_template('admin/addpost_admin.html',title=u'添加文章',cats=cats,tags=tags,SITE_TITLE=setting.SITE_TITLE,BASE_URL=setting.BASE_URL)

@app.route('/admin/edit_post',methods=['GET', 'POST'])
@login_required
def admin_editpost():
    _article = None
    if request.method == 'POST':
        post_id = request.form.get('id', '')
        if request.form.get('act', '')=='editpost':
            _post_type = request.form.get('post_type', '')
            if _post_type == '':
                _post_type = 0
            _tags = request.form.get('tags', '').replace(u'，',',')
            tagslist = set([x.strip() for x in _tags.split(',')])
            try:
                tagslist.remove('')
            except:
                pass
            if tagslist:
                _tags = ','.join(tagslist)
            imgsrc = re.search("img src=(\S*)", request.form.get('content', ''))
            imgthumbnail = ''
            if imgsrc:
                imgext = re.search("(\.\w*)$", imgsrc.group(1))
                if imgext:
                    logging.error(">>admin_addpost: %s" % imgsrc.group(1)+"_thumbnail"+ imgext.group(1))
                    imgthumbnail = imgsrc.group(1)+"_thumbnail"+ imgext.group(1)
            operatorDB.update_article(request.form.get('id', ''),
                                      request.form.get('category', ''),
                                      request.form.get('title', ''),
                                      request.form.get('content', ''),
                                      _tags,request.form.get('password', ''),
                                      shorten_content(request.form.get('content', '')),
                                      imgthumbnail, _post_type,
                                      request.form.get('editor_title', '')
                                              )
            if _tags!='':
                operatorDB.add_postid_to_tags(_tags.split(','), str(post_id))
            operatorDB.add_postid_to_cat(request.form.get('category', ''),str(post_id))
            
        
        _article = operatorDB.detail_post_by_id(post_id)
        
    cats = operatorDB.get_all_cat_name()
    tags = operatorDB.get_all_tag_name()
    return render_template('admin/editpost_admin.html',obj=_article,cats=cats,tags=tags,SITE_TITLE=setting.SITE_TITLE,BASE_URL=setting.BASE_URL)

@app.route('/admin/del_post/<int:post_id>')
@login_required
def admin_delpost(post_id):
	operatorDB.del_post_by_id(post_id)
	return redirect(url_for('admin_editpost'))

@app.route('/admin/comment',methods=['GET', 'POST'])
@login_required
def admin_editcomment():
	comments = None
	if request.method == 'GET':
		print('----------admin_editcomment-----GET--------')
		if request.args.get('act', '')=='del':
			commentid = request.args.get('commentid', '')
			operatorDB.del_comment_by_id(commentid)
			post_id = request.args.get('post_id', '')
			comments = operatorDB.get_post_comments(post_id)
	if request.method == 'POST':
		post_id = request.form.get('id', '')
		comments = operatorDB.get_post_comments(post_id)
	return render_template('admin/editcomment_admin.html',comments=comments,SITE_TITLE=setting.SITE_TITLE,BASE_URL=setting.BASE_URL)

@app.route('/uploadFile',methods=['GET', 'POST'])
def uploadFile():
    if request.method == 'POST':
        file = request.files['Filedata']
        file_url = ''
        new_file_name = ''
        if file:
            filename = secure_filename(file.filename)
            try:
                file_type = filename.split('.')[-1].lower()
                new_file_name = "%d.%s"% (int(time.time()), file_type)
            except:
                file_type = ''
                new_file_name = str(int(time.time()))
            if setting.debug:
                file.save(os.path.join(app.config['UPLOAD_FOLDER'],new_file_name))
            else:
                encoding = None
                if "*.png;*.jpg;*.jpeg;*.gif;".find(file_type) != -1:#图片
                    img = Image.open(StringIO(file.stream.read()))
                    file_url, thumbnail_url = put_obj2storage(file_name = new_file_name, data = img.tostring('jpeg', 'RGB'), expires='365', type= file.content_type, encoding= encoding)
                else:
                    file_url, thumbnail_url = put_obj2storage(file_name = new_file_name, data = file.stream.read(), expires='365', type= file.content_type, encoding= encoding)
    logging.error("==>uploadfile: %s, thumbnail file:%s" % (file_url, thumbnail_url))  
    ret = {}
    ret["imgUrl"] = file_url
    ret["thumbnailUrl"] = thumbnail_url
    file_url_json = json.dumps(ret)
    return file_url_json

def shorten_content(htmlstr='',sublength=80):
    result = re.sub(r'<[^>]+>', '', htmlstr)
    result = result.replace("&nbsp;","")
    return result[0:sublength]

def addTimelineData():
	_list = operatorDB.getArticleAllForTimeline()
	_data = ''
	for _article in _list:
		startDate = time.strftime('%Y,%m,%d',time.localtime(_article._add_time))
		headline = _article._title
		text = '%s --- %sdetailpost/%s' % (_article._category,setting.BASE_URL,_article._id)
		_data = '%s,{"startDate":"%s","headline":"%s","text":"%s","asset":{"media":"","credit":"","caption":""}}' % (_data,startDate,headline,text)
	operatorDB.saveTimelineData(_data[1:])

def updateTimelineData(_article):
	timelineData = operatorDB.getTimelineData()
	startDate = time.strftime('%Y,%m,%d',time.localtime(_article._add_time))
	headline = _article._title
	text = '%s --- %sdetailpost/%s' % (_article._category,setting.BASE_URL,_article._id)
	_data = '%s,{"startDate":"%s","headline":"%s","text":"%s","asset":{"media":"","credit":"","caption":""}}' % (timelineData.timeline_data,startDate,headline,text)
	operatorDB.saveTimelineData(_data,timelineData.id)