from django.contrib import admin
from django.conf import settings

from news import models
from .tasks import send_email_with_news
from utils.admin import BaseModelAdminMixin


@admin.register(models.NewsType)
class NewsTypeAdmin(admin.ModelAdmin):
    """News type admin."""
    list_display = ['id', 'name']
    list_display_links = ['id', 'name']


def send_email_action(modeladmin, request, queryset):
    news_ids = list(queryset.values_list("id", flat=True))
    if settings.USE_CELERY:
        send_email_with_news.delay(news_ids)
    else:
        send_email_with_news(news_ids)


send_email_action.short_description = "Send the selected news by email"


class NewsGalleryInline(admin.TabularInline):
    """News gallery inline."""
    model = models.NewsGallery
    extra = 0


@admin.register(models.News)
class NewsAdmin(BaseModelAdminMixin, admin.ModelAdmin):
    """News admin."""
    raw_id_fields = ('address',)
    actions = [send_email_action]
    raw_id_fields = ('news_type', 'address', 'country')
    inlines = [NewsGalleryInline, ]


@admin.register(models.NewsGallery)
class NewsGalleryAdmin(admin.ModelAdmin):
    """News gallery admin."""
