#!python
# coding: utf-8

from __future__ import absolute_import, print_function

import os
from docopt import docopt
from pyquery import PyQuery
from markdown_css import parse_style

from pygments import highlight
from pygments.lexers import get_lexer_by_name, get_all_lexers
from pygments.formatters import HtmlFormatter
from pygments.styles import get_style_by_name


def special_process_wechat_ol_ul(html):
    while len(html("ul")) > 0:
        result = []
        for li in html("ul").eq(0).find("li"):
            result.append('<span style="display:block" ><span style="margin-right: 10px;" >•</span>' + PyQuery(li).html() + '</span>')

        html("ul").eq(0).replaceWith('<p>' + ''.join(result) + '</p>')

    while len(html("ol")) > 0:
        result = []
        index = 1
        for li in html("ol").eq(0).find("li"):
            result.append('<span style="display:block" ><span style="margin-right: 10px;" >' +
                          str(index) + '.</span>' + PyQuery(li).html() + '</span>')
            index += 1

        html("ol").eq(0).replaceWith('<p>' + ''.join(result) + '</p>')

    return html


def special_process_code(html):
    all_langs = support_langs()
    # print(all_langs)
    for pre in html("pre"):
        lang = PyQuery(pre).attr("lang")
        if not lang:
            lang = PyQuery(pre.find("code")).attr("lang")
        if lang:
            lang = lang.lower()
        if lang == "shell":
            lang = "bash"
        if lang in all_langs:
            codeHtml = highlightcode(lang, PyQuery(pre).text())
            html(pre).replaceWith(codeHtml)

    return html


def support_langs():
    all_support_languages = []
    for i in get_all_lexers():
        all_support_languages.append(i[0].lower())
    return set(all_support_languages)


def highlightcode(lang, code):
    lexer = get_lexer_by_name(lang, stripall=True)
    formatter = HtmlFormatter(cssclass="highlight", style=get_style_by_name('colorful'))
    return highlight(code, lexer, formatter)


def main(input_file, out, style, name, render, codehighlight):
    if not os.path.isdir(out):
        print('warning : %s is not a dir' % out)
        return

    if not name.endswith('.html'):
        name += '.html'

    out_path = os.path.join(out, name)
    if not os.path.isfile(style):
        print('warning : %s is not file' % style)
        return

    with open(input_file, 'r', encoding='utf-8') as in_f:
        content = in_f.read()
    
    with open(style, 'r', encoding='utf-8') as style_f:
        style_content = style_f.read()
    
    e_list, e_dict, p_list = parse_style(style_content)
    html = PyQuery(content)
    if render == 'wechat':
        html = special_process_wechat_ol_ul(html)
    if codehighlight == 'yes':
        html = special_process_code(html)
    for k in e_list:
        for css in e_dict[k].split(';'):
            name_value = css.split(':')
            if not name_value:
                continue
            if len(name_value) != 2:
                continue
            html(k).css(name_value[0], name_value[1])

    if p_list:
        style = PyQuery('<style type="text/css"></style>')
        style('style').html('\n'.join(p_list))
        html('head').append(style)

    with open(out_path, 'w', encoding='utf-8') as out_f:
        out_f.write(html.html(method='html'))


if __name__ == '__main__':
    helpdoc = """markdown-css command line.
    Usage:
    markdown-css (-h | --help)
    markdown-css <input> [--out=<out>] [--name=<name>] [--style=<style>] [--render=<render>] [--codehighlight=<codehighlight>]

    Options:
    -h,  --help        Show help document
    --out=<out> Html out path [default: 'public']
    --name=<name> Out file name [default: <input>]
    --style=<style> Markdown css file [default: 'style.css']
    --render=<render> Html render by wechat or not [default: 'wechat']
    --codehighlight=<codehighlight> Highlight code yes or no [default: 'no']
    """
    rgs = docopt(helpdoc)
    input_file = rgs.get('<input>')
    out = rgs.get('--out')
    style = rgs.get('--style')
    name = rgs.get('--name')
    render = rgs.get('--render')
    codehighlight = rgs.get('--codehighlight')
    if not out:
        out = 'public'
    if not style:
        style = 'style.css'
    if not name:
        name = input_file
    if not render:
        render = 'wechat'
    if not codehighlight:
        codehighlight = 'no'

    main(input_file, out, style, name, render, codehighlight)
