import json

from django import template
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from django.utils.safestring import mark_safe

from aircox.serializers.admin import UserSettingsSerializer

__all__ = ("register", "do_get_admin_tools", "do_formset_inline_data", "do_inline_labels")


register = template.Library()


@register.simple_tag(name="get_admin_tools")
def do_get_admin_tools():
    return admin.site.get_tools()


@register.simple_tag(name="formset_inline_data", takes_context=True)
def do_formset_inline_data(context, formset):
    """Return initial data of formset as dict (used by TrackListEditor and
    PlaylistEditor). Keys are:

    - ``items``: list of items. Extra keys:
        - ``__error__``: dict of form fields errors
    - ``settings``: user's settings
    - ``fields``: dict of field name and label
    """

    # --- get fields labels
    model = formset.form.Meta.model
    fields = {}
    for field_name in formset.form.Meta.fields:
        field = model._meta.get_field(field_name)
        fields[field_name] = str(field.verbose_name).capitalize()

    # --- get items
    items = []
    for form in formset.forms:
        item = {name: form[name].value() for name in form.fields.keys()}
        item["__errors__"] = form.errors

        # hack for sound list
        if duration := item.get("duration"):
            item["duration"] = duration.strftime("%H:%M")
        if sound := getattr(form.instance, "sound"):
            item["name"] = sound.name
            fields["name"] = str(_("Sound")).capitalize()

        # hack for playlist editor
        tags = item.get("tags")
        if tags and not isinstance(tags, str):
            item["tags"] = ", ".join(tag.name for tag in tags)
        items.append(item)

    data = {"items": items, "fields": fields}
    user = context["request"].user
    settings = getattr(user, "aircox_settings", None)
    data["settings"] = settings and UserSettingsSerializer(settings).data
    source = json.dumps(data)
    return source


inline_labels_ = {
    # list editor
    "add_item": _("Add an item"),
    "remove_item": _("Remove"),
    "save_settings": _("Save Settings"),
    "discard_changes": _("Discard changes"),
    "submit": _("Submit"),
    "delete": _("Delete"),
    # select file
    "upload": _("Upload"),
    "list": _("List"),
    "confirm_delete": _("Are you sure to remove this element from the server?"),
    "show_next": _("Show next"),
    "show_previous": _("Show previous"),
    "select_file": _("Select a file"),
    # track list
    "columns": _("Columns"),
    "timestamp": _("Timestamp"),
    # sound list
    "add_sound": _("Add a sound"),
}


@register.simple_tag(name="inline_labels")
def do_inline_labels():
    """Return labels for columns in playlist editor as dict."""
    return mark_safe(json.dumps({k: str(v) for k, v in inline_labels_.items()}))
