import pipes
from subprocess import Popen, PIPE

from django.utils.encoding import smart_text

from assetfiles.filters import BaseFilter, ExtensionMixin


class CoffeeScriptFilter(ExtensionMixin, BaseFilter):
    """
    Filters CoffeeScript files into JS.
    """
    input_ext = 'coffee'
    output_ext = 'js'

    def filter(self, input):
        command = 'coffee --compile --print {0}'.format(
            pipes.quote(input))

        process = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
        stdout, stderr = process.communicate()

        if process.returncode:
            raise CoffeeScriptFilterError(stderr)
        else:
            return stdout


class CoffeeScriptFilterError(Exception):
    """
    CoffeeScriptError parses syntax errors generated by CoffeeScript and
    formats them for Django.
    """
    pass
