# coding=utf-8
# -------------------------------------------------------------------------------
# Author: Alexandre Manhaes Savio <alexsavio@gmail.com>
# Grupo de Inteligencia Computational <www.ehu.es/ccwintco>
# Universidad del Pais Vasco UPV/EHU
#
# 2015, Alexandre Manhaes Savio
# Use this at your own risk!
# -------------------------------------------------------------------------------

import os
import re
import logging
import os.path as op

from   sys    import platform as _platform

LOGGING_LVL = logging.INFO
logging.basicConfig(level=LOGGING_LVL)


def find_file_match(folder_path, regex=''):
    """
    Returns absolute paths of files that match the regex within folder_path and
    all its children folders.

    Note: The regex matching is done using the match function
    of the re module.

    Parameters
    ----------
    folder_path: string

    regex: string

    Returns
    -------
    A list of strings.

    """
    outlist = []
    for root, dirs, files in os.walk(folder_path):
        outlist.extend([op.join(root, f) for f in files
                        if re.match(regex, f)])

    return outlist


def is_exe(fpath):
    """Return True if fpath is an executable file path.

    Parameters
    ----------
    fpath: str
        File path

    Returns
    -------
    is_executable: bool
    """
    return op.isfile(fpath) and os.access(fpath, os.X_OK)


def which(program):
    """
    :param program:
    :return:
    """
    fpath, fname = op.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 = op.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None


def get_system_path():
    if _platform == "linux" or _platform == "linux2":
        return os.environ['PATH']
    elif _platform == "darwin":
        return os.environ['PATH']
    elif _platform == "win32":
        # don't know if this works
        return os.environ['PATH']


def get_other_program_folders():
    if _platform == "linux" or _platform == "linux2":
        return ['/opt/bin']
    elif _platform == "darwin":
        return ['/Applications', op.join(os.environ['HOME'], 'Applications')]
    elif _platform == "win32":
        # don't know if this works
        return ['C:\Program Files']


def get_temp_dir():
    if _platform == "linux" or _platform == "linux2":
        return None
    elif _platform == "darwin":
        return '.'
    elif _platform == "win32":
        # don't know if this works
        return None


def find_in_other_programs_folders(app_name):
    app_name_regex = '^' + app_name + '$'
    other_folders  = get_other_program_folders()

    for folder in other_folders:
        abin_file = find_program(folder, app_name_regex)
        if abin_file is not None:
            return abin_file

    return None


def find_program(root_dir, exec_name):
    file_matches = find_file_match(root_dir, exec_name)
    for f in file_matches:
        if is_exe(f):
            return f
    return None


def ask_for_path_of(app_name):
    bin_path = None
    while bin_path is not None:
        bin_path = input('Insert path of {} executable file [Press Ctrl+C to exit]: '.format(app_name))

        if not op.exists(bin_path):
            print('Could not find file {}. Try it again.'.format(bin_path))
            bin_path = None
            continue

        if not is_exe(bin_path):
            print('No execution permissions on file {}. Try again.'.format(bin_path))
            bin_path = None
            continue

        return bin_path


def proactive_search_of(app_name):
    if _platform == 'win32':
        bin_name = app_name + '.exe'
    else:
        bin_name = app_name

    bin_path = which(app_name)
    if bin_path is not None and is_exe(bin_path):
        return bin_path

    bin_path = find_in_other_programs_folders(bin_name)
    if bin_path is not None:
        return bin_path

    return ask_for_path_of(bin_name)


def get_inkscape_binpath():
    return proactive_search_of('inkscape')


def get_lyx_binpath():
    return proactive_search_of('lyx')


#TEMPLATES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')

# JINJA_ENV = Environment(loader=PackageLoader('docstamp', 'templates'))
#JINJA_ENV = Environment(loader=FileSystemLoader(TEMPLATES_DIR))

# FILE_EXPORTERS = {'.svg': Inkscape,}
#                   '.tex': PdfLatex,
#                   '.lyx': LyX}

@@ -443,15 +443,19 @@
 ath 
+     
 as op%0A
-%0A
 from
@@ -464,16 +464,22 @@
  sys    
+      
 import p
@@ -500,16 +500,58 @@
 atform%0A%0A
+from   .commands    import which, is_exe%0A%0A
 LOGGING_
@@ -1185,673 +1185,8 @@
 st%0A%0A
-%0Adef is_exe(fpath):%0A    %22%22%22Return True if fpath is an executable file path.%0A%0A    Parameters%0A    ----------%0A    fpath: str%0A        File path%0A%0A    Returns%0A    -------%0A    is_executable: bool%0A    %22%22%22%0A    return op.isfile(fpath) and os.access(fpath, os.X_OK)%0A%0A%0Adef which(program):%0A    %22%22%22%0A    :param program:%0A    :return:%0A    %22%22%22%0A    fpath, fname = op.split(program)%0A    if fpath:%0A        if is_exe(program):%0A            return program%0A    else:%0A        for path in os.environ%5B%22PATH%22%5D.split(os.pathsep):%0A            path = path.strip('%22')%0A            exe_file = op.join(path, program)%0A            if is_exe(exe_file):%0A                return exe_file%0A%0A    return None%0A%0A%0A
 def 

Remove which function from config.py