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

import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import os, shutil, sys, re
import platform
from mm2xhtml.MixedMark import mm2xhtml
from cStringIO import StringIO

mm2xhtmlType = 'normal'

graphvizCommand = 'dot '
graphvizFont = ''
gnuplotCommand = 'gnuplot '
gnuplotFont = ''
if platform.uname()[0].startswith('CYGWIN'):
    graphvizFont = '-Gfontname="MSGOTHIC.TTC" -Nfontname="MSGOTHIC.TTC" -Efontname="MSGOTHIC.TTC" '
    gnuplotFont = 'C:\WINDOWS\Fonts\msgothic.ttc'
elif platform.uname()[0] == 'Windows':
    graphvizFont = '-Gfontname="MSGOTHIC.TTC" -Nfontname="MSGOTHIC.TTC" -Efontname="MSGOTHIC.TTC" '
    gnuplotFont = 'C:\WINDOWS\Fonts\msgothic.ttc'
elif platform.uname()[0] == 'Darwin':
    graphvizFont = '-Gfontname="HiraMaruPro-W4" -Nfontname="HiraMaruPro-W4" -Efontname="HiraMaruPro-W4" '
    gnuplotFont = 'HiraMaruPro-W4'
elif platform.uname()[0] == 'Linux':
    graphvizFont = '-Gfontname="san serif" -Nfontname="san serif" -Efontname="san serif" '
    gnuplotFont = '/usr/share/fonts/truetype/ttf-ipafonts/ipag.ttf'

for a in sys.argv:
    if a == '-s5':
        mm2xhtmlType = 's5'
        
class MyHTTPRequestHandler(SimpleHTTPRequestHandler):
    """Mixed Mark"""
    def do_GET(self):
        last = self.requestline.split(' ')[1].split('?',1)
        path = self.translate_path(last[0])
        if os.path.isdir(path):
            if os.path.exists(path+'/index.mm'):
                path = path+'/index.mm'
        if len(last)==1:
            parameter={}
        else:
            parameter={}
            for pare in last[1].split('&'):
                p = pare.split('=',1)
                if len(p)==1:
                    parameter[p[0]] = ''
                else:
                    parameter[p[0]] = p[1]
        if path.endswith('.mm'):
            self.send_MixedMark(path,parameter)
        elif path.endswith('.dot'):
            self.send_graphviz(path,parameter)
        elif path.endswith('.gp'):
            self.send_gnuplot(path,parameter)
        else:
            SimpleHTTPRequestHandler.do_GET(self)

    def send_MixedMark(self,path,parameter):
        mm2xhtmlChapter = -1
        if parameter.has_key('chapter'):
            mm2xhtmlChapter = int(parameter['chapter'])
        f = None
        try:
            f = open(path,'r')
        except IOError:
            self.send_error(404, "File not found")
            return None
        output = StringIO()
        mm2xhtml(f,output,mm2xhtmlType,mm2xhtmlChapter)
        mm = output.getvalue()
        f.close()
        output.close()
        self.send_response(200)
        self.send_header("Content-type", 'application/xhtml+xml')
        self.send_header("Content-Length", str(mm.__len__()))
        self.end_headers()
        self.wfile.write(mm)

    def send_graphviz(self,path,parameter):
        if len(parameter.keys())==0:
            f = None
            try:
                f = open(path,'r')
            except IOError:
                self.send_error(404, "File not found")
                return None
            mm = f.read()
            self.send_response(200)
            self.send_header("Content-type", 'text/plain')
            self.send_header("Content-Length", str(mm.__len__()))
            self.end_headers()
            self.wfile.write(mm)
        else:
            ext = '-Tpng '
            mimetype = 'image/png'
            if parameter.has_key('format'):
                t=parameter['format']
                if t=='svg':
                    ext = '-Tsvg '
                    mimetype = 'image/svg+xml'
                elif t=='jpg':
                    ext = '-Tjpg '
                    mimetype = 'image/jpeg'
            commandLine = graphvizCommand + graphvizFont + ext
            commandLine = commandLine + path
            input, output = os.popen2(commandLine,"b")
            input.close()
            mm = output.read()
            self.send_response(200)
            self.send_header("Content-type", mimetype)
            self.send_header("Content-Length", str(mm.__len__()))
            self.end_headers()
            self.wfile.write(mm)

    def send_gnuplot(self,path,parameter):
        if len(parameter.keys())==0:
            f = None
            try:
                f = open(path,'r')
            except IOError:
                self.send_error(404, "File not found")
                return None
            mm = f.read()
            self.send_response(200)
            self.send_header("Content-type", 'text/plain')
            self.send_header("Content-Length", str(mm.__len__()))
            self.end_headers()
            self.wfile.write(mm)
        else:
            terminal = "set terminal png font '"+gnuplotFont+"'\n"
            mimetype = 'image/png'
            if parameter.has_key('format'):
                t=parameter['format']
                if t=='svg':
                    terminal = "set terminal svg\n"
                    mimetype = 'image/svg+xml'
                elif t=='jpg':
                    terminal = "set terminal jpeg font '"+gnuplotFont+"'\n"
                    mimetype = 'image/jpeg'
            commandLine = gnuplotCommand
            input, output = os.popen2(commandLine,"b")
            input.write(terminal)
            f = open(path)
            input.write(f.read())
            f.close()
            input.write("\n")
            input.close()
            mm = output.read()
            output.close()
            if mimetype == 'image/svg+xml':
                mm = self.fixSVG(mm)
            self.send_response(200)
            self.send_header("Content-type", mimetype)
            self.send_header("Content-Length", str(mm.__len__()))
            self.end_headers()
            self.wfile.write(mm)

    #gnuplot4.0の出すsvgはデフォルトネームスペースの設定が
    #無いので，とりあえず場当たり的な方法で対処
    def fixSVG(self,mm):
        if mm.find('xmlns="http://www.w3.org/2000/svg"') == -1:
            p = re.compile('<svg')
            mm = p.sub('<svg xmlns="http://www.w3.org/2000/svg"',mm,1)
        return mm

#BaseHTTPServer.test(MyHTTPRequestHandler,BaseHTTPServer.HTTPServer)
MyHTTPRequestHandler.extensions_map['.svg'] = 'image/svg+xml'
MyHTTPRequestHandler.extensions_map['.svgz'] = 'image/svg+xml'
print 'Serving HTTP on 0.0.0.0 port 8000 ...'
BaseHTTPServer.HTTPServer(('',8000),MyHTTPRequestHandler).serve_forever()
