"""This module holds the django admin models of the ``themes`` app."""

import re

from django.contrib import admin

from .models import Theme


def duplicate(modeladmin, request, queryset):  # pylint: disable=unused-argument
    """Duplicate instances in queryset.

    To duplicate a theme, we remove the primary key to create a new instance
    when we call ``save`` method. And we reset synchronisation references.

    """

    for theme in queryset:

        theme.pk = None
        theme.last_update = None
        theme.first_update = None

        # We generate a new name based on duplicated theme and we flag it as not default
        old_name = re.split(r'\(\d+\)$', theme.name)[0].strip()
        number = Theme.objects.non_deleted().filter(name__startswith=old_name).count()
        theme.name = "%s (%d)" % (old_name, number + 1)
        theme.default = False
        theme.save()

duplicate.short_description = "Duplicate selected themes"


class ThemeAdmin(admin.ModelAdmin):
    """Django admin model for the ``Theme`` model."""

    list_display = ('name', 'default')
    actions = (duplicate,)


admin.site.register(Theme, ThemeAdmin)
