"""
===========================
RevAssets
===========================

Makes possible for python web apps to work with hashed static assets
generated by other tools like Gulp or Webpack.

It does so by reading the manifest generated by the revision tool.

"""
import json
import io


__version__ = '1.0.3'


class AssetNotFound(Exception):
    pass


class RevAssets(object):
    """
    Map the source -> hashed assets

    :param base_url: From where the hashed assets are served.
    :param reload: Reload the manifest each time an asset is requested.
    :param manifest: Path and filename of the manifest file.
    :param quiet: If False, a missing asset will raise an exception

    """

    def __init__(self, base_url='/static', reload=False,
                 manifest='manifest.json', quiet=True):
        self.base_url = base_url.rstrip('/')
        self.reload = reload
        self.manifest = manifest
        self.assets = {}
        self.quiet = quiet

    def _load_manifest(self):
        with io.open(self.manifest, 'rt', encoding='utf-8') as mf:
            return json.loads(mf.read())

    def asset_url(self, asset):
        if not self.assets or self.reload:
            self.assets = self._load_manifest()
        asset = asset.strip('/')
        path = self.assets.get(asset)
        if not path:
            if self.quiet:
                return ''
            msg = 'Asset file {!r} not found'.format(asset)
            raise AssetNotFound(msg)

        return '{}/{}'.format(
            self.base_url,
            path.lstrip('/'),
        )
