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

import os, sys, glob, string
from email.Parser import HeaderParser
from mm2xhtml.markdown2 import markdown
from mm2xhtml.pukiwikiDL import text_to_dl
from mm2xhtml.pukiwikiTable import text_to_table
from mm2xhtml.transToXHTML import transToXHTML
from mm2xhtml.transToS5 import transToS5, transToS5Body
from mm2xhtml.mmPostProcess import mmPostProcess
from mm2xhtml.mm_include import mm_include
from mm2xhtml.pickOutChapter import pickOutChapter
from mm2xhtml.itex2mml import itex2mml

usage ="""mm2xhtml Usage:
    mm2xhtml [options] [file [file ...]]
        options
            -body
            -s5
            -s5body
            -c0, -c1, ...
        if you do not specify files,
        mm2xhtml works as a filter.
"""

def parseHEADER(inText):
    m = HeaderParser().parsestr(inText)
    return (m.items(), m.get_payload())

def mm2xhtml_file(inFile,outFile,type='body',chapter=-1):
    inString = inFile.read()
    outFile.write(mm2xhtml(inString,type,chapter))

def mm2xhtml(inString,type='body',chapter=-1):
    mm = inString
    header, mm = parseHEADER(mm)
    mm = mm_include(mm)
    mm = text_to_dl(mm)
    mm = text_to_table(mm)
    mm = itex2mml(mm)
    mm = markdown(mm)
    if chapter!=-1:
        mm = pickOutChapter(mm,chapter)
    body = mmPostProcess(mm)
    if type == 'normal':
        return transToXHTML(body,header)
    elif type == 'body':
        return body
    elif type == 's5':
        return transToS5(body,header)
    elif type == 's5body':
        return transToS5Body(body,header)
    return body

def mmMain(sys_argv):
    chapter = -1
    type = 'normal'
    args = []
    for a in sys.argv:
        if a == '-body':
            type = 'body'
        elif a == '-s5':
            type = 's5'
        elif a == '-s5body':
            type = 's5body'
        elif a.startswith('-c'):
            chapter = int(a[2:])
        elif a.startswith('-'):
            print usage
            sys.exit(0)
        else:
            args.append(a)

    if len(args) == 1:
        inFile = sys.stdin
        outFile = sys.stdout
        mm2xhtml_file(inFile,outFile,type,chapter)
    else:
        print args[1:]
        for f in args[1:]:
            g = glob.glob(f);
            if len(g) == 0:
                print '???file %s does not exist???' % f
                continue
            inFile = open(f)
            co = string.rfind(f,'.mm')
            if co == -1:
                ff = f + '.xhtml'
            else:
                ff = f[:co] + '.xhtml'
            outFile = open(ff,'w')
            mm2xhtml_file(inFile,outFile,type,chapter)
            inFile.close()
            outFile.close()
