"""This module holds the widgets for the ``common`` app"""

from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe

from floppyforms.widgets import DateInput

try:
    STATIC_URL_BASE = settings.STATIC_URL
except AttributeError:
    try:
        STATIC_URL_BASE = settings.MEDIA_URL
    except AttributeError:
        STATIC_URL_BASE = ''


class FarbtasticColorPicker(forms.TextInput):
    """
    Based on http://colpick.com/plugin
    """
    class Media:
        css = {'all': (STATIC_URL_BASE + 'trainings/farbtastic/farbtastic.css',)}
        # pylint: disable=invalid-name
        js = (STATIC_URL_BASE + 'trainings/farbtastic/farbtastic.js',)

    def _get_colorpicker_id(self, input_id):
        """
        Return the HTML id for the colorpicker.
        """
        return '%s-colorpicker' % input_id

    def _render_js(self, input_id, value):  # pylint: disable=unused-argument
        color_picker_id = self._get_colorpicker_id(input_id)
        # pylint: disable=invalid-name
        js = """
<script type="text/javascript">
    $(document).ready(function(){
        var $pickerEl = $('#%s');
        var $inputEl = $('#%s');
        $pickerEl.farbtastic('#'+$inputEl.attr('id'));
        $pickerEl.hide();
        $inputEl.focus(function(){
            $pickerEl.show();
        }).on('blur', function(){
            $pickerEl.hide();
        });
    });
</script>""" % (color_picker_id, input_id)
        return js

    def _render_html(self, name, value, attrs=None):
        rendered_input = super(FarbtasticColorPicker, self).render(name, value, attrs)
        colorpicker_id = self._get_colorpicker_id(attrs['id'])
        html = """
            <div style="position: relative;">
                %s
                <div id="%s" class="farbtastic" style="position: absolute; bottom: 30px;"></div>
            </div>
        """ % (rendered_input, colorpicker_id)
        return html

    def render(self, name, value, attrs=None):
        if 'id' not in attrs:
            attrs['id'] = "id_%s" % name
        return mark_safe(self._render_html(name, value, attrs) +
                         self._render_js(attrs['id'], value))


class DateRangeInput(forms.MultiWidget):
    """Widget to select a range of date

    Notes
    -----
    Made to work with the ``django_filters.fields.DateRangeField`` field.

    """

    def __init__(self, attrs=None):
        """Init the input with a tuple of two ``DatePicker`` widgets

        For the parameters, see ``django.forms.MultiWidget"""

        widgets = (DateInput(attrs=attrs), DateInput(attrs=attrs))

        super().__init__(widgets, attrs)

    def decompress(self, value):
        """Returns a list of decompressed values for the given compressed value.

        The given value can be assumed to be valid, but not necessarily non-empty.

        Parameters
        ----------
        value: list
            list of values, each corresponding to a widget

        """

        if value:
            return [value.start, value.stop]
        return [None, None]

    def format_output(self, rendered_widgets):
        """Given a list of rendered widgets (as strings), returns a Unicode string
        representing the HTML for the whole lot.

        Parameters
        ----------
        rendered_widgets: list
            A list of the rendered html widgets

        Returns
        -------
        str
            The formatted html of all the widgets

        """

        return ' - '.join(rendered_widgets)
