# --
# Copyright (c) 2012-2014 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
# --

from .comp import Gallery, Asset, AssetCropper
from nagare import presentation, var, ajax, security
from nagare.i18n import _, _N


def render_image(self, h, comp, size, randomize=False, **kw):
    metadata = self.assets_manager.get_metadata(self.filename)
    src = self.assets_manager.get_image_url(self.filename, size)
    if randomize:
        src += '?r=' + h.generate_id()
    return h.img(title=metadata['filename'], alt=metadata['filename'],
                 src=src, **kw)


def render_file(self, h, comp, size, **kw):
    kw['class'] += ' file_icon'
    metadata = self.assets_manager.get_metadata(self.filename)
    res = [h.img(title=metadata['filename'], alt=metadata['filename'],
                 src="img/file-icon.jpg", **kw)]
    if size == 'medium':
        res.append(h.span(metadata['filename']))
    return res

CONTENT_TYPES = {'image/png': render_image,
                 'image/jpeg': render_image,
                 'image/pjpeg': render_image,
                 'image/gif': render_image}


@presentation.render_for(Gallery)
def render(self, h, comp, *args):
    with h.div(class_='nbItems'):
        h << h.script(u'YAHOO.kansha.app.closeModal();')
        h << comp.render(h, model='badge')
    with h.div(id="card-gallery"):
        if security.has_permissions('edit', self):
            for overlay in self.overlays:
                h << overlay
        else:
            for asset in self.assets:
                h << asset.render(h, model="anonymous")

    return h.root


@presentation.render_for(Gallery, "download")
def render_download(self, h, comp, *args):
    if security.has_permissions('edit', self):
        v_file = var.Var()
        submit_id = h.generate_id("attach_submit")
        input_id = h.generate_id("attach_input")
        h << h.label((h.i(class_='icon-file icon-grey'),
                      _("Add file")), class_='btn btn-small', for_=input_id)
        with h.form:
            h << h.script(
                u'''