#! /usr/bin/env python

import os
import sys
import subprocess
import datetime
import time
import argparse

def is_exe(fpath):
    """

    """
    return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

def which(program):
    """
    This function is taken from http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
    """
    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None

def getext(filename):
    "Get the file extension."

    return os.path.splitext(filename)[-1].lower()

def compile(output_type, input_file, pandoc_options, logging):

    # Files are installed by setuptools one directory higher in the tree than th pandoc-gpp script
    macros_file = os.path.dirname(__file__) + "/../../include/macros.gpp"
    if logging == True:
            print "[log] : Path -> " + os.path.dirname(__file__) + "/.."
    command = "export PANDOC_GPP_PATH="+ os.path.dirname(__file__) + "/../..;" +" gpp --include "+ macros_file +" -x -D"+output_type.upper()+"=1 -T "+ input_file  +" | pandoc " + pandoc_options

    if logging == True:
        print "[log] : Command -> " + command
    os.chdir(os.path.abspath(os.getcwd()))
    try :
        output = subprocess.check_output(command,stderr=subprocess.STDOUT,shell=True)
        if logging == True:
            print "[log] : Output -> " + output
            print "[log] : No error found"
    except subprocess.CalledProcessError as err:
        print "Error : " + err.output
        #print "Error append"

def parseOptions():
    pandoc_output = subprocess.Popen(["pandoc", "--help"], stdout=subprocess.PIPE).communicate()[0]
    added_epilog = '\n'.join(pandoc_output.split("\n")[1:])
    epilog = "-------------------------------------------\nPandoc standard options are: \n\n" + added_epilog
    #print epilog
    parser = argparse.ArgumentParser(description="gpp overlay for pandoc compilation", epilog=epilog,formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("-t", "--to", dest="to", default="pdf", help="destination format")
    parser.add_argument("-f", "--from", dest="origin", help="source format")
    parser.add_argument("-o", "--output", dest="output", help="output file")
    parser.add_argument("-l", "--log", dest="log", help="log output to stdout")
    parser.add_argument("input_file", help="input file to process")

    args = parser.parse_known_args()

    if "pdf" in args[0].output:
        pandoc_options = " -f " + args[0].origin + " " + ' '.join(args[1]) + " -o " + args[0].output
    else :
        pandoc_options = "-t " + args[0].to +  " -f " + args[0].origin + "+grid_tables " + ' '.join(args[1]) + " -o " + args[0].output

    #print pandoc_options

    if args[0].log :
        logging = True
    else :
        logging = False

    if not pandoc_options :
        print "pandoc options must be provided!\n"
        parser.print_help()
        exit()

    return (args[0].to,args[0].input_file, pandoc_options, logging)

def main():

    options = parseOptions()

    if options[3] == True:
        print "[log] : Options -> " + str(options)


    compile(options[0], options[1], options[2], options[3])

if __name__ == '__main__':
    pandoc_path = which("pandoc")
    gpp_path = which("gpp")
    if not pandoc_path or not gpp_path :
        message = """pandoc and gpp executable must be in the path to be used by pandoc-gpp!

 - pandoc is available here : http://johnmacfarlane.net/pandoc/ (installing section)

 - gpp sources are available here : https://github.com/dloureiro/gpp
"""
        print message
        exit()
    main()
