# coding:utf-8
from django.db.models.loading import get_model
from django.forms import MultiWidget, HiddenInput, TextInput
from django.utils.safestring import mark_safe


class LookupPopupWidget(MultiWidget):
    def __init__(self, model, lookup_view_url, attrs=None, model_loader=get_model, **kwargs):
        self.model = model
        self.url = lookup_view_url

        self.search_button_label = kwargs['search_button_label']
        self.height = kwargs['height']
        self.width = kwargs['width']
        self.model_loader = model_loader

        widgets_list = (HiddenInput(), TextInput())

        super(LookupPopupWidget, self).__init__(widgets_list, attrs)

    def decompress(self, value):
        if value:
            model = self.model_loader(self.model)
            instance = model.objects.get(pk=value)
            return [instance.pk, str(instance)]

        return [None, None]

    def render(self, name, value, attrs=None):
        widget_rendering = super(LookupPopupWidget, self).render(name, value, attrs)

        template = "{0} <button type='button' id='{1}' onclick=\"{2}\">{3}</button>"

        popup_call = self._build_javascript_popup_call(name)

        final_html = template.format(widget_rendering, name, popup_call, self.search_button_label)

        return mark_safe(final_html)

    def _build_javascript_popup_call(self, name):
        template = "window.open('{0}', '{1}', 'width={2},height={3}')"

        return template.format(self.url, name, self.width, self.height)
