
import json
import os

from apps.core.utils.config_manager import update_config
from django import forms
from django.conf import settings
from django.contrib import admin, messages
from django.http import HttpResponseRedirect

from ..models.theme_settings import Theme
from .mixins import SingletonAdminMixin


def set_theme_config(request, obj):
    update_config("Theme", {"themename": str(obj.themename)})


class ThemeForm(forms.ModelForm):

    class Meta:
        model = Theme
        fields = '__all__'
        widgets = {'themename': forms.HiddenInput()}


@admin.register(Theme)
class ThemeAdmin(SingletonAdminMixin, admin.ModelAdmin):
    form = ThemeForm
    change_form_template = 'admin/core/theme/change_form.html'

    def change_view(self,
                    request,
                    object_id=None,
                    form_url='',
                    extra_context=None):
        instance = Theme.get_solo()
        themes = Theme.get_available_themes()
        current_theme = next(
            (t for t in themes if t['dirname'] == instance.themename), None)

        # 改进的设置合并逻辑
        current_settings = {}
        if current_theme:
            # 从主题配置中提取默认设置
            theme_default_settings = {}
            for setting in current_theme.get('settings', []):
                theme_default_settings[setting['name']] = setting['default']

            current_settings = {
                **theme_default_settings,
            }

        extra_context = extra_context or {}
        extra_context.update({
            'themes': themes,
            'current_theme': current_theme,
            'current_settings': json.dumps(current_settings),
        })
        return super().change_view(request, object_id, form_url, extra_context)

    def response_change(self, request, obj):
        if '_select-theme' in request.POST:
            theme_name = request.POST.get('selected_theme')
            if theme_name:
                obj.themename = theme_name
                # 切换到新主题时重置设置
                obj.theme_settings = {}
                obj.save()
                messages.success(request, f'主题已成功切换为{obj.themename}')
                set_theme_config(request, obj)
                return HttpResponseRedirect(request.path)

        if '_save-theme-settings' in request.POST:
            theme_name = request.POST.get('theme_name')

            # 获取当前主题配置
            themes = Theme.get_available_themes()
            current_theme = next(
                (t for t in themes if t['dirname'] == theme_name), None)

            if not current_theme:
                messages.error(request, '主题配置不存在')
                return HttpResponseRedirect(request.path)

            # 读取原始主题配置文件
            try:
                theme_path = os.path.join(settings.BASE_DIR, 'templates',
                                          'themes', theme_name,
                                          'themesettings.json')

                with open(theme_path, 'r', encoding='utf-8') as f:
                    theme_settings = json.load(f)
            except Exception as e:
                messages.error(request, f'读取主题配置文件失败: {str(e)}')
                return HttpResponseRedirect(request.path)

            # 处理表单数据并更新默认值
            for key in request.POST:
                if key.startswith('setting_'):
                    setting_name = key.replace('setting_', '')
                    value = request.POST[key]

                    # 查找对应的设置定义以确定类型
                    setting_def = next(
                        (s for s in theme_settings.get('settings', [])
                         if s['name'] == setting_name), None)

                    if setting_def:
                        # 根据类型转换值
                        if setting_def.get('type') == 'checkbox':
                            value = value.lower() == 'true'
                        elif setting_def.get('type') == 'number':
                            try:
                                if '.' in value:
                                    value = float(value)
                                else:
                                    value = int(value)
                            except (ValueError, TypeError):
                                value = setting_def.get('default', 0)
                        elif value.lower() in ['true', 'false']:
                            value = value.lower() == 'true'
                        elif value.isdigit():
                            value = int(value)
                        elif value.replace('.', '', 1).isdigit():
                            value = float(value)

                        # 更新默认值
                        setting_def['default'] = value
            # 保存更新后的主题配置文件
            try:
                with open(theme_path, 'w', encoding='utf-8') as f:
                    json.dump(theme_settings, f, ensure_ascii=False, indent=2)

                messages.success(request, '主题设置已成功保存到主题配置文件')
            except Exception as e:
                messages.error(request, f'保存主题设置到配置文件时出错: {str(e)}')

            return HttpResponseRedirect(request.path)

        return super().response_change(request, obj)
