#!/usr/bin/env python

from __future__ import print_function

from rstweaver import rst_to_doc, weaver_css, register_all_languages
from rstweaver.languages import all_languages
from rstweaver.context import get_weaver_context

from argparse import ArgumentParser
import sys
import re

parser = ArgumentParser(
    description = 'Transform reST literate code to formatted document'
)

parser.add_argument('source', metavar='SOURCE', type=str, nargs='*',
    help='reST source files')
parser.add_argument('--css', dest='css', action='store_true', default=True,
    help='Include <style> tags in the document')
parser.add_argument('--no-css', dest='css', action='store_false',
    help='Don\'t include <style> tags in the document')
parser.add_argument('-o', dest='outpath', type=str, default='',
    help='Specify output file')
parser.add_argument('-t', '--output-format', dest='output_format', default='html',
    help='Specify output format. It should be one that docutils can produce.')
parser.add_argument('-f', '--fragment', dest='fragment', action='store_true', default=True,
    help='Don\'t include <html>, <body> etc (the default)')
parser.add_argument('-u', '--full', dest='fragment', action='store_false',
    help='Do include <html>, <body> etc (not the default)')
parser.add_argument('--print-css', dest='printcss', action='store_true', default=False,
    help='Print CSS and exit')

args = parser.parse_args()

format_names = {
    'latex'     : 'latex',
    'tex'       : 'latex',
    'odt'       : 'odf_odt'
}

extensions = {
    'tex'        : 'tex',
    'latex'      : 'tex',
    'odf_odt'    : 'odt'
}

def run(path, source):
    wd = path + '-weaver'
    
    return rst_to_doc(
        source,
        languages     = all_languages,
        wd            = wd,
        css           = args.css,
        full          = not args.fragment,
        output_format = format_names.get(args.output_format, args.output_format)
    )

def open_output(path):
    if path == '-':
        return sys.stdout
    return open(path, 'w')

def print_to_outpath(inpath, content):
    if inpath == None:
        if args.outpath == '':
            sys.stdout.write(content)
        else:
            with open_output(args.outpath) as hl:
                hl.write(content)
    else:
        if args.outpath == '':
            ext = extensions.get(args.output_format, args.output_format)
            outpath = re.sub(r'\.[^.]*', '.' + ext, inpath)
        else:
            outpath = args.outpath
        
        with open_output(outpath) as hl:
            hl.write(content)
 
if args.printcss:
    register_all_languages()
    context = get_weaver_context()
    print_to_outpath(None, weaver_css(context))
    sys.exit(0)

if len(args.source) == 0:
    source = sys.stdin.read()
    body = run('./stdin', source)
    
    print_to_outpath(None, body)

for inpath in args.source:
    with open(inpath, 'r') as infile:
        source = infile.read()

    body = run(inpath, source)
    print_to_outpath(inpath, body)

