from django.forms import widgets
from django.utils.safestring import mark_safe

# custom date and datetime picker widgets
# for easier css/js integration, would be a mess to do this
# via the template engine


class CustomDateWidget(widgets.DateInput):
    def __init__(self, attrs=None):
        widgets.DateInput.__init__(self, attrs)

    def render(self, name, value, attrs=None):
        render = super(widgets.DateInput, self).render(name, value, attrs)
        html_start = mark_safe('<div class="input-control text" data-role="datepicker" data-position="top"' \
                               ' style="z-index: 1100;" data-format="yyyy-mm-dd">')
        html_end = mark_safe('<button type="button" class="btn-date"></button></div>')
        return widgets.format_html('{0}{1}{2}', html_start, render, mark_safe(html_end))


class CustomDateTimeWidget(widgets.SplitDateTimeWidget):
    def __init__(self, attrs=None):
        widgets.SplitDateTimeWidget.__init__(self, attrs)
        super(widgets.SplitDateTimeWidget, self).__init__([CustomDateWidget(),
                                                           widgets.TimeInput(attrs={'data-field': 'time'})])

    def format_output(self, rendered_widgets):
        html = rendered_widgets[0]
        html += "</div><div class='input-control text'>"
        html += rendered_widgets[1]
        return mark_safe(html)


class NumberWithUnitWidget(widgets.NumberInput):
    suffix = None

    def __init__(self, attrs=None, suffix=None):
        self.suffix = suffix
        widgets.NumberInput.__init__(self, attrs)
        super(widgets.NumberInput, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        html = '<div class="input-control number"><nobr>'

        render = super(widgets.NumberInput, self).render(name, value, attrs)
        html += render

        # dirty trick this
        if self.suffix:
            html += '<span style="margin-left: -40px; white-space: nowrap;">' + self.suffix + '</span>'

        html += '</nobr></div>'
        return mark_safe(html)