from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import os
import re
import string
import subprocess
import tempfile
import time
import traceback

from makesticker import makesticker
from makeplanche import makeplanche

PORT = 8000
OUT_DIR = tempfile.gettempdir()
TEMPLATE_DIR = '/data'
DEFAULT_DPI = 300


def inkscapize(svg_in, pdf_out):
    png_out = tempfile.mktemp(suffix='.png')
    try:
        cmd = ['inkscape', '--export-type=png', f'--export-filename={png_out}',
                f'--export-dpi={DEFAULT_DPI}', svg_in]
        subprocess.check_call(cmd)

        cmd = ['convert', png_out, pdf_out]
        subprocess.check_call(cmd)
    finally:
        if os.path.exists(png_out):
            os.unlink(png_out)


def parse_request(request):
    request = json.loads(request)

    # fill in sticker details
    sticker_out = tempfile.mktemp(suffix='.svg')

    try:
        with open(sticker_out, 'w') as stickout:
            landscape = request.get('landscape', False)
            print(f'landscape: {landscape}')
            makesticker(os.path.join(TEMPLATE_DIR, request['sticker']), stickout,
                    request['subs'], landscape=landscape)

        # make sticker sheet
        planche_out = tempfile.mktemp(suffix='.svg')
        with open(sticker_out, 'r') as stickin:
            with open(planche_out, 'w') as planchout:
                makeplanche(stickin, planchout)

        # process to printable pdf
        pdf_out = tempfile.mktemp(dir=OUT_DIR, suffix='.pdf')
        inkscapize(planche_out, pdf_out)

        response = {'status': 'ok', 'file': os.path.basename(pdf_out),
                'message': 'this is the way'}
        return json.dumps(response)

    finally:
        if os.path.exists(sticker_out):
            os.unlink(sticker_out)
        if 'planche_out' in locals() and os.path.exists(planche_out):
            os.unlink(planche_out)


class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        if re.match(r'/data/\w+\.pdf', self.path) is not None:
            if not os.path.exists(self.path):
                self.send_response(404)
                self.end_headers()
                return
            self.send_response(200)
            self.send_header("Content-type", "application/pdf")
            self.end_headers()
            with open(self.path, 'rb') as f:
                self.wfile.write(f.read())
            return

        self.send_response(200)
        self.send_header("Content-type", "text/html; charset=UTF-8")
        self.end_headers()
        self.wfile.write(b"<html><head><title>Zetikettes</title></head>")
        self.wfile.write(b"<body>")
        self.wfile.write("<p>This is not the way.</p>".encode())
        self.wfile.write(b"</body></html>")

    def do_POST(self):
        try:
            length = int(self.headers['content-length'])
            req = self.rfile.read(length).decode()
            resp = parse_request(req).encode()
        except:
            self.send_response(500)
            self.send_header("Content-type", "text/plain")
            self.end_headers()
            self.wfile.write(traceback.format_exc().encode())
            raise

        self.send_response(200)
        self.send_header("Content-type", "application/json")
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        self.wfile.write(resp)


if __name__ == "__main__":        
    webServer = HTTPServer(('', PORT), MyServer)
    print(f"Server started on port {PORT}")

    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass

    webServer.server_close()
    print("Server stopped.")
