import json

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

from aircox.serializers.admin import UserSettingsSerializer

__all__ = ("register", "do_get_admin_tools", "do_track_inline_data")


register = template.Library()


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


@register.simple_tag(name="track_inline_data", takes_context=True)
def do_track_inline_data(context, formset):
    """Return initial data for playlist editor as dict. Keys are:

    - ``items``: list of items. Extra keys:
        - ``__error__``: dict of form fields errors
    - ``settings``: user's settings
    """
    items = []
    for form in formset.forms:
        item = {name: form[name].value() for name in form.fields.keys()}
        item["__errors__"] = form.errors

        # 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}
    user = context["request"].user
    settings = getattr(user, "aircox_settings", None)
    data["settings"] = settings and UserSettingsSerializer(settings).data
    source = json.dumps(data)
    return source


track_inline_labels_ = {
    "artist": _("Artist"),
    "album": _("Album"),
    "title": _("Title"),
    "tags": _("Tags"),
    "year": _("Year"),
    "save_settings": _("Save Settings"),
    "discard_changes": _("Discard changes"),
    "columns": _("Columns"),
    "add_track": _("Add a track"),
    "remove_track": _("Remove"),
    "timestamp": _("Timestamp"),
}


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