from apps.core.models.site_settings import SiteSettings
from django.contrib import admin

from .mixins import SingletonAdminMixin


@admin.register(SiteSettings)
class SiteSettingsAdmin(SingletonAdminMixin, admin.ModelAdmin):

    # 字段分组显示
    fieldsets = (
        (
            "基础配置",
            {
                "fields": (
                    "site_name",
                    "site_title",
                    "site_url",
                    "logo",
                    "meta_keywords",
                    "meta_description",
                    "copyright",
                    "global_js",
                )
            },
        ),
        ("时区、语言", {"fields": ("language_code", "time_zone")}),
        ("联系信息", {"fields": ("company_name", "webmaster", "master_phone", "webmaster_email")}),
    )

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        if not obj or not obj.site_url:
            form.base_fields["site_url"].initial = request.get_host()
        return form

    def save_model(self, request, obj, form, change):
        protocol = request.META.get("HTTP_X_FORWARDED_PROTO", "http")
        host = request.META.get("HTTP_X_FORWARDED_HOST", request.get_host())
        if not obj.site_url:
            obj.site_url = f"{protocol}://{host}"
        if obj.site_url.endswith("/"):
            obj.site_url = obj.site_url[:-1]
        super().save_model(request, obj, form, change)
