#==============================================================================
# Copyright (C) 2011 by Loïc Grobol
#
# This file is part of CTESLO.
# 
#    CTESLO is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
# 
#    CTESLO is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
# 
#    You should have received a copy of the GNU General Public License
#    along with CTESLO.  If not, see <http://www.gnu.org/licenses/>.
#==============================================================================

"""
Created on 12 juil. 2011

@author: Loïc Grobol <loic.grobol@gmail.com>

Misc utilities and shortcuts
"""

import formats
from importlib import import_module
import tempfile, os, sys, functools, subprocess
ROOT = sys.path[0]

def _format_tool(in_stream, out_stream,
                 file_format, *options, tool):
    """Execute a tool given by a format (e.g. the cleaner
       for transcriber_export_fr).
       Formats' tools are meant to be filters in -> tool -> out,
       but you can use *options to pass any other argument if needed.
       """

    try: # Get the file_format's tool's path
        file_format = dynamic_import("formats." + file_format)
        tool_exec = os.path.join(ROOT, "formats", file_format.NAME, getattr(file_format, tool))

    except (AttributeError, TypeError): # Fallback to default tool's path 
        tool_exec = os.path.join(ROOT, "formats", getattr(formats, tool))

    with tempfile.TemporaryDirectory(prefix=".cteslo_") as temp:
        # Temp files
        in_file = os.path.join(temp, "in")
        out_file = os.path.join(temp, "out")

        # Output the input stream content inside a temp file
        copy(in_stream, in_file)
        # clean the input -> clean
        subprocess.call(" ".join((tool_exec, "-i", in_file, "-o", out_file) + options), shell=True)
        # Output the result
        copy(out_file, out_stream)

textify = functools.partial(_format_tool, tool="TEXTIFIER")
formatify = functools.partial(_format_tool, tool="FORMATIFIER")
columnize = functools.partial(_format_tool, tool="COLUMNIZER")

def dynamic_import(module):
    try:
        return import_module(module)
    # If the module  has already been imported
    except TypeError:
        return module

def copy(source, destination):
    """Copy a stream/file into another."""
    try:
        source_content = source.read()
    except AttributeError:  #Most certainly %source is a str
        with open(source, 'r') as ifile:
            source_content = ifile.read()
    try:
        destination.write(source_content)
    except AttributeError:
        with open(destination, 'w') as ofile:
            ofile.write(source_content)

class temporary_files_collection:
    """A handy shortcut to handle large collections of temp files.
       >>> t = temporary_files_collections("/usr/bin/something")
       >>> print(t.whatever)
       /usr/bin/something_whatever
    """
    def __init__(self, prefix):
        self._prefix = prefix
        self._files = {}

    def __getattr__(self, name):
        if name in self._files: return self._files[name]
        self._files[name] = "{0}_{1}".format(self._prefix, name)
        return self._files[name]
