# -*- coding: utf-8 -*-

import os.path

from django import forms
from django.utils.safestring import mark_safe
from django.utils.html import escape, conditional_escape

class ClearableFileInputNoURL(forms.ClearableFileInput):
    '''
       Subclass of ClearableFileInputNoURL which shows an URL to the PolyNum 
       download view.
    '''
    template_with_initial = u'%(initial_text)s:\
 %(initial)s %(clear_template)s<br />%(input_text)s: %(input)s'

    template_with_clear = u'%(clear_checkbox_label)s &nbsp;%(clear)s'

    def render(self, name, value, attrs=None):
        substitutions = {
            'initial_text': self.initial_text,
            'input_text': self.input_text,
            'clear_template': '',
            'clear_checkbox_label': self.clear_checkbox_label,
        }
        template = u'%(input)s'
        substitutions['input'] = forms.FileInput.render(self, name, value, attrs)

        if value and hasattr(value, "url"):
            template = self.template_with_initial
            substitutions['initial'] = (u'<a target="_blank" href="../../download/{0}">{0}</a>'
                                    .format(escape(os.path.basename(value.name))))
            if not self.is_required:
                checkbox_name = self.clear_checkbox_name(name)
                checkbox_id = self.clear_checkbox_id(checkbox_name)
                substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)
                substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)
                substitutions['clear'] = forms.CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})
                substitutions['clear_template'] = '&nbsp;<form method="post"><input type="submit" name="delete-uploadfile" class="button" value="Supprimer">'

        return mark_safe(template % substitutions)


class MillerColumns(forms.HiddenInput):
    is_hidden = False

    class Media:
        css = {
                'all': ( 'eo/css/eo.millercolumns.css', ),
        }
        js = ( 'jquery/js/jquery-ui.js',
               'eo/js/eo.millercolumns.js',
               'eo/js/eo.django.millercolumns.widget.js')

    def render(self, name, value, attrs=None):
        extra = []
        extra.append(super(MillerColumns, self).render(name, value, attrs))
        extra.append(u'''<div data-target="{0}" class="django-miller-columns-widget"></div>'''.format(attrs['id']))
        return mark_safe('\n'.join(extra))
