#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'Jiayi Li'

import time
from datetime import datetime

import mistune
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')


def datetime_filter(t):
    
    '''custom datetime filter for jinja2 templates'''
    
    delta = int(time.time() - t)
    if delta <= 1:
        return u'a second ago'
    if delta < 60:
        return u'%s seconds ago' % delta
    if delta < 120:
        return u'a minute ago'
    if delta < 3600:
        return u'%s minutes ago' % (delta // 60)
    if delta < 7200:
        return u'an hour ago'
    if delta < 86400:
        return u'%s hours ago' % (delta // 3600)
    if delta < 172800:
        return u'a day ago'
    if delta < 604800:
        return u'%s days ago' % (delta // 86400)
    dt = datetime.fromtimestamp(t)
    return u'%s %s, %s' % (months[dt.month-1], dt.day, dt.year)


class HighlightRenderer(mistune.Renderer):
    
    '''
    custom renderer for mistune markdown parser
    '''
    
    def block_code(self, code, lang):
        if not lang or 'python3':
            return '\n<pre><code>%s</code></pre>\n' % mistune.escape(code)
        lexer = get_lexer_by_name(lang or 'python3', stripall=True)
        formatter = HtmlFormatter()
        return highlight(code, lexer, formatter)
    
    
renderer = HighlightRenderer()
markdown = mistune.Markdown(renderer=renderer, hard_wrap=True)

def markdown_filter(text):
    return markdown(text)
@@ -1209,22 +1209,15 @@
     
-if not lang or
+guess =
  'py
@@ -1222,17 +1222,16 @@
 python3'
-:
 %0A       
@@ -1235,74 +1235,265 @@
     
+%0A
     
-return '%5Cn%3Cpre%3E%3Ccode%3E%25s%3C/code%3E%3C/pre%3E%5Cn' %25 mistune.escape(code)
+    if code.lstrip().startswith('#include'):%0A            guess = 'c++'%0A        elif code.lstrip().startswith('%3C'):%0A            guess = 'html'%0A        elif code.lstrip().startswith(('function', 'var', '$')):%0A            guess = 'javascript'%0A            
 %0A   
@@ -1531,25 +1531,21 @@
 lang or 
-'python3'
+guess
 , stripa

revise highlight renderer