# coding=utf-8
from dal.autocomplete import ViewMixin
from dal_select2.widgets import WidgetMixin, Select2WidgetMixin
from django.views.generic.list import View
from django import forms
from django.http import JsonResponse
from django.utils.html import format_html
from django.utils.encoding import force_text


class BaseAutocompleteListView(ViewMixin, View):
    def get_list_by_query(self, q):
        """"Return the list of tuples(id, text) from which to autocomplete."""
        raise NotImplementedError

    def get(self, request, *args, **kwargs):
        """"Return option list json response."""
        results = self.get_list_by_query(self.q)

        data = {
            'results': [dict(id=k, text=v) for k, v in results]
        }

        return JsonResponse(data)


class LongListSelect(forms.Select):
    def get_selected_options(self, selected_choices):
        raise NotImplementedError

    def render_options(self, selected_choices):
        options = self.get_selected_options(selected_choices)
        # Normalize to strings.
        selected_choices = set(force_text(v) for v in selected_choices)
        output = []
        for option_value, option_label in options:
            if isinstance(option_label, (list, tuple)):
                output.append(format_html('<optgroup label="{}">', force_text(option_value)))
                for option in option_label:
                    output.append(self.render_option(selected_choices, *option))
                output.append('</optgroup>')
            else:
                output.append(self.render_option(selected_choices, option_value, option_label))
        return '\n'.join(output)


class LongListSelectWidget(WidgetMixin, Select2WidgetMixin, LongListSelect):
    pass
