#! /usr/bin/env python3
# -*- coding: iso-8859-15 -*-
"""
Created on Sun May 24 22:56:25 2015

@author: Le Bouquin
"""
from subprocess import call
import numpy as np
import argparse
import os

def find_block (lines, start, end):
    s = np.where (np.array([start in l for l in lines]))[0][0] + 1
    e = np.where (np.array([end in l for l in lines]))[0][0]
    return [o for o in lines[s:e] if o is not '']

recipe_start = r'\begin{tabularx}{\textwidth}{p{0.35\textwidth}p{0.6\textwidth}}'
recipe_end   = r'\end{tabularx}'

step_start = r'\begin{enumerate}'
step_end = r'\end{enumerate}'

input_start = r'\begin{tabularx}{0.85\textwidth}{|p{0.3\textwidth}|p{0.55\textwidth}|} \hline'
input_end   = r'\hline \end{tabularx}'
input_label  = r'DO.CATG & short description \\ \hline \hline'

output_label = r'PRO.CATG & short description \\ \hline \hline'
param_label  = r'Name & short description\\ \hline \hline'

usage = """
description:
   Convert online help of a recipe into a TEX-friendly to be pasted into the manual.
"""

examples = """
examples:
   run_make_help.py gravity_vis
   run_make_help.py --recipe-dir=~/pipeline gravity_vis                                                         
"""

#
# Implement options
#

parser = argparse.ArgumentParser(description=usage, epilog=examples, formatter_class=argparse.RawDescriptionHelpFormatter)

parser.add_argument('recipe', nargs='+', help='recipe name', type=str)

parser.add_argument("--recipe-dir", dest="recipe_dir", default=None, help="Option for esorex")                  
#
# Main program
#

if __name__ == "__main__":

    args = parser.parse_args()

    recipe = args.recipe[0]
    print ('')
    print(('Build help for recipe '+recipe+':'))
    print ('\n\n\n')
                                                                                                             
    # Build the system call                                                                                     
    syscal = 'esorex -man';                                                                                     
    if (args.recipe_dir is not None):
        syscal = syscal + ' -recipe-dir='+args.recipe_dir                         

    # Call esorex
    os.system (syscal+' '+recipe+' > toto.txt')
    f = open('toto.txt', 'r') # 'r' = read
    lines = f.readlines()
    f.close()
    
    # Cleanup from '\n' and empty lines
    lines = [l.rstrip() for l in lines if l.rstrip() is not '']
    
    print ('')
    print(('\subsection{'+recipe.replace('_','\_')+'}'))
    
    block = find_block (lines, 'DESCRIPTION', 'Reduction steps:')
    for l in block:
        print((l.replace('_','\_')))

    block = find_block (lines, 'Reduction steps:', 'CATG in input SoF')[1:]
    print (step_start)
    for l in block:
        print ((l.replace('_','\_').replace(' * ',' \item ')))
    print (step_end)
    
    print ('')
    print ('\subsubsection*{Input}')

    block = find_block (lines, 'CATG in input SoF', 'PRO.CATG of products')[1:]
    print (input_start)
    print (input_label)
    for l in block:
        print(((l.replace('_','\_').replace(' : ',' & '))+'  \\\\'))
    print (input_end)
    
    print ('')
    print ('\subsubsection*{Output}')
    
    block = find_block (lines, 'PRO.CATG of products','OPTIONS')[1:]
    print (input_start)
    print (output_label)
    for l in block:
        print(((l.replace('_','\_').replace(' : ',' & '))+'  \\\\'))
    print (input_end)
    
    print ('')
    print ('\subsubsection*{Parameters}')
    
    block = find_block (lines,'OPTIONS','possible to create a configuration file')[1:]
    print (input_start)
    print (param_label)
    for l in block:
        print((l.replace('_','\_').replace(': ',' & ').replace(']',']\\\\')))
    print (input_end)

    
