#! /usr/bin/python3
# -*- coding-utf-8 -*-

"""
This script transform a md into a plain html in the context of a
documentation for Kit&Pack.
"""

import mmap
import yaml

print("---------------------------- geo --")
print("-- by antoine.delhomme@espci.org --")
print("-----------------------------------")

doc_in = "./001-v2-doc"

class geoReader():

    def __init__(self, doc_name):
        self.doc_name = doc_name
        self.doc_in = "%s.md" % self.doc_name
        self.doc_out = ""

        self.f_in = None
        self.f_in_mmap = None

        self.header = None
        self.header_limit = -1

    def __enter__(self):
        """Open the file.
        """

        self.f_in = open(self.doc_in, 'r')

        return self

    def __exit__(self, type, value, traceback):
        """Close the file.
        """
        self.f_in.close()

    def parseHeader(self):
        """Parse the header of the file.
        """

        if self.header_limit < 0:
            self.f_in_mmap = mmap.mmap(self.f_in.fileno(),
                    0, access=mmap.ACCESS_READ)
            self.header_limit = self.f_in_mmap.find(b'---')

            if self.header_limit != -1:
                self.header = yaml.load(
                        self.f_in_mmap[0:self.header_limit])
            else:
                raise("Cannot load the header")

    def parseLine(self, line):
        """Parse a line.
        """

        rejected = ["---\n", "\n"]

        if line in rejected:
            line_parsed = ""
        elif line[0] == "#":
            line_parsed = "\n<h2>%s</h2>\n" % line[2:]
        else:
            line_parsed = "\n<p>%s</p>\n" % line

        return line_parsed

    def parse(self):
        """Parse all the document.
        """

        # Parse the header
        self.parseHeader()

        # Init the output file
        self.doc_out = "%s.php" % self.header['version']

        with open(self.doc_out, 'w') as f_out:
            # Write down the header
            # ... version
            f_out.write(
                    "<p>Documentation %s</p>\n"
                    % self.header["version"])

            # ... parts list
            f_out.write("\n")
            f_out.write(
                "<section id=r\"partsList\">\n" \
                "<h2>Composants</h2>\n" \
                "<dl>\n")

            for item in self.header["items"]:
                src = "../i/doc/%s/%s" % (
                    self.header["version"],
                    item["img"])

                f_out.write(
                        "   <dt><img src=\"%s\" /></dt>\n" \
                        "   <dd>%s</dd>\n" % (
                        src, item["description"]))

            f_out.write(
                    "</dl>\n" \
                    "\n" \
                    "</section>\n")

            # ... intro
            f_out.write("\n")
            f_out.write(
                    "<section id=\"doc\">\n" \
                    "<h2>Notice de montage</h2>")

            # Parse the rest of the document
            self.f_in.seek(self.header_limit)

            for line in self.f_in.readlines():
                # Parse the line
                line_parsed = self.parseLine(line)

                # Write it out
                f_out.write(line_parsed)


# Read the document
with geoReader(doc_in) as g:
    g.parse()

@@ -600,16 +600,69 @@
 t = -1%0A%0A
+        # Parsing flags%0A        self.pf_inP = False%0A%0A
     def 
@@ -1488,15 +1488,35 @@
 -%5Cn%22
-, %22%5Cn%22%5D
+%5D%0A%0A        line_parsed = %22%22
 %0A%0A  
@@ -1566,21 +1566,23 @@
 _parsed 
++
 = %22%22%0A
+%0A
         
@@ -1630,23 +1630,24 @@
 sed 
++
 = %22%5Cn%3Ch
-2
+3
 %3E%25s%3C/h
-2
+3
 %3E%5Cn%22
@@ -1656,17 +1656,20 @@
  line%5B2:
-%5D
+-1%5D%0A
 %0A       
@@ -1663,36 +1663,152 @@
 :-1%5D%0A%0A        el
-se:%0A
+if line == %22%5Cn%22:%0A            if self.pf_inP:%0A                # Close a paragrah%0A                self.pf_inP = False%0A    
             line
@@ -1819,32 +1819,233 @@
 sed 
++
 = %22
-%5Cn%3Cp%3E%25s%3C/p%3E%5Cn
+%3C/p%3E%5Cn%22%0A            else:%0A                line_parsed += %22%22%0A%0A        else:%0A            if not self.pf_inP:%0A                self.pf_inP = True%0A                line_parsed += %22%5Cn%3Cp%3E%22%0A%0A            line_parsed += %22%25s 
 %22 %25 line
 %0A%0A  
@@ -2040,16 +2040,21 @@
 %22 %25 line
+%5B:-1%5D
 %0A%0A      
@@ -2134,32 +2134,91 @@
 ent.%0A        %22%22%22
+%0A        %0A        # Reset flags%0A        self.pf_inP = False
 %0A%0A        # Pars
@@ -3429,16 +3429,18 @@
 age%3C/h2%3E
+%5Cn
 %22)%0A%0A    
@@ -3732,16 +3732,252 @@
 arsed)%0A%0A
+            # Close any open paragraph%0A            if self.pf_inP:%0A                self.pg_inP = False%0A                f_out.write(%22%3C/p%3E%5Cn%22)%0A%0A            # ... ending%0A            f_out.write(%22%5Cn%22)%0A            f_out.write(%22%3C/section%3E%22)%0A%0A
 %0A# Read 

Parse paragraph