from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned

from staff.users.models import User


CENTER_MASTER = getattr(settings, 'СENTER_MASTER', 'center.yandex-team.ru')


class AutocompleteWidget(forms.MultiWidget):

    class Media:
        js = (
            'https://%s/media/js/_js-autocomplete_staff.js' % CENTER_MASTER,
        )

    def __init__(self, attrs=None, to_field_name='id', model=None):
        attrs = attrs or {}
        if 'onclick' not in attrs:
            attrs['onclick'] = "return {hidden: '%s'}" % to_field_name

        self.to_field_name = to_field_name
        widgets = (forms.TextInput(attrs=attrs), forms.HiddenInput())
        self.widgets = [isinstance(w, type) and w() or w for w in widgets]

        super(AutocompleteWidget, self).__init__(widgets=widgets, attrs=attrs)
        self._model = model

    def render(self, name, value, attrs=None):

        if self.is_localized:
            for widget in self.widgets:
                widget.is_localized = self.is_localized

        if not isinstance(value, list):
            value = self.decompress(value)
        output = []
        final_attrs = self.build_attrs(attrs)
        id_ = final_attrs.get('id', None)
        for i, widget in enumerate(self.widgets):
            try:
                widget_value = value[i]
            except IndexError:
                widget_value = None
            if id_:
                final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))

            if i == 1:
                output.append(
                    widget.render(name + '__%s' % self.to_field_name, widget_value))
            else:
                output.append(widget.render(name, widget_value, final_attrs))

        return mark_safe(self.format_output(output))

    def value_from_datadict(self, data, files, name):
        return (
            self.widgets[0].value_from_datadict(data, files, name),
            self.widgets[1].value_from_datadict(data, files, name + '__%s' % self.to_field_name)
        )

    def decompress(self, value):

        if not value:
            return [None, None]

        try:
            instance = self._model.objects.get(pk=value)
            return [str(instance), getattr(instance, self.to_field_name)]
        except (self._model.DoesNotExist, self._model.MultipleObjectsReturned):
            return [None, None]


class StaffUserAutocompleteWidget(AutocompleteWidget):

    def decompress(self, value):

        if not value:
            return [None, None]

        try:
            user = User.objects.get(pk=value)
            instance = self._model.objects.get(login_ld=user.username)
            return [str(instance), getattr(instance, self.to_field_name)]
        except (ObjectDoesNotExist, MultipleObjectsReturned):
            return [None, None]
