# Path: webpack/compiler.py
# def webpack(config_file, context=None, settings=None, manifest=manifest_reader, compiler=build_server):
#     use_manifest = conf.settings.USE_MANIFEST
# 
#     # Allow the USE_MANIFEST setting to be overridden when populating the manifest
#     if settings:
#         use_manifest = settings.get('USE_MANIFEST', use_manifest)
# 
#     if use_manifest:
#         return manifest.read(config_file, context)
# 
#     return compiler.build(
#         config_file=config_file,
#         extra_context=context,
#         setting_overrides=settings,
#     )
# 
# Path: webpack/exceptions.py
# class BundlingError(Exception):
#     pass


import sys
from django.template import Library
from optional_django import six
from ..compiler import webpack
from ..exceptions import BundlingError

register = Library()


@register.assignment_tag(name='webpack')
def webpack_template_tag(path_to_config):
    """
    A template tag that will output a webpack bundle.

    Usage:

        {% load webpack %}
        
        {% webpack 'path/to/webpack.config.js' as bundle %}

        {{ bundle.render_css|safe }}

        {{ bundle.render_js|safe }}
    """

    # TODO: allow selection of entries

    # Django's template system silently fails on some exceptions
    try:
        return webpack(path_to_config)
    except (AttributeError, ValueError) as e:

# Path: webpack/compiler.py
# def webpack(config_file, context=None, settings=None, manifest=manifest_reader, compiler=build_server):
#     use_manifest = conf.settings.USE_MANIFEST
# 
#     # Allow the USE_MANIFEST setting to be overridden when populating the manifest
#     if settings:
#         use_manifest = settings.get('USE_MANIFEST', use_manifest)
# 
#     if use_manifest:
#         return manifest.read(config_file, context)
# 
#     return compiler.build(
#         config_file=config_file,
#         extra_context=context,
#         setting_overrides=settings,
#     )
# 
# Path: webpack/exceptions.py
# class BundlingError(Exception):
#     pass


# Path: webpack/templatetags/webpack.py
import sys
from django.template import Library
from optional_django import six
from ..compiler import webpack
from ..exceptions import BundlingError


register = Library()


@register.assignment_tag(name='webpack')
def webpack_template_tag(path_to_config):
    """
    A template tag that will output a webpack bundle.

    Usage:

        {% load webpack %}
        
        {% webpack 'path/to/webpack.config.js' as bundle %}

        {{ bundle.render_css|safe }}

        {{ bundle.render_js|safe }}
    """

    # TODO: allow selection of entries

    # Django's template system silently fails on some exceptions
    try:
        return webpack(path_to_config)
    except (AttributeError, ValueError) as e:

        raise six.reraise(BundlingError, BundlingError(*e.args), sys.exc_info()[2])