from django.contrib import admin
from django.urls import path
from django.shortcuts import redirect
from django.contrib import messages
from .models import BotConfig
from .models import BotConfig, WelcomeMessage, BotMessage, BotEventMessageConfig
from .tasks import restart_bot_container

@admin.register(BotConfig)
class BotConfigAdmin(admin.ModelAdmin):
    change_form_template = "admin/botconfig_change_form.html"

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path(
                "<int:botconfig_id>/restart/",
                self.admin_site.admin_view(self.restart_bot),
                name="botconfig-restart"
            ),
        ]
        return custom_urls + urls

    def restart_bot(self, request, botconfig_id):
        try:
            BotConfig.objects.get(id=botconfig_id)
        except BotConfig.DoesNotExist:
            self.message_user(request, "Настройка бота с таким ID не найдена.", level=messages.ERROR)
            return redirect("..")

        restart_bot_container.delay()
        self.message_user(request, "Бот будет перезапущен в фоновом режиме.", messages.SUCCESS)
        return redirect("..")

@admin.register(WelcomeMessage)
class WWelcomeMessageAdmin(admin.ModelAdmin):
    list_display = ("bot", "welcome_message", "welcome_image", "admin_contact", "channel_link", "group_link", "custom_link1_name", "custom_link1_url")
    
@admin.register(BotMessage)
class BotMessageAdmin(admin.ModelAdmin):
    list_display = ("name", "text", "image", "buttons_json")

@admin.register(BotEventMessageConfig)
class BotEventMessageConfigAdmin(admin.ModelAdmin):
    list_display = ("event", "message", "enabled")
    list_filter = ("event", "enabled")