import json
from django.db import models
from django.core.exceptions import ValidationError
import os
import configparser
from django.conf import settings
from django.utils.translation import gettext_lazy as _  # 添加导入
from .common import ConfigCommonModel
import re
from django.core.management import call_command


def validate_folder_name(folder_name):
    # 定义正则表达式：仅允许英文、数字和下划线，且至少一个字符
    pattern = r'^[a-zA-Z0-9_]+$'
    # 使用fullmatch确保整个字符串匹配
    return re.fullmatch(pattern, folder_name) is not None


class Theme(ConfigCommonModel):
    THEME_DIR = os.path.join(settings.BASE_DIR, 'templates/themes')
    themename = models.CharField(
        verbose_name=_('模板名称'),  # 使用gettext_lazy翻译
        max_length=50,
        default='default',
        blank=True,
        help_text=_("选择下方模板后保存切换主题")  # 翻译帮助文本
    )

    class Meta:
        verbose_name = _('主题风格配置')  # 翻译单数名称
        verbose_name_plural = _('主题风格配置')  # 翻译复数名称

    def __str__(self):
        return str(_("主题风格配置"))  # 使用str()确保返回字符串类型

    @classmethod
    def get_available_themes(cls):
        """
        获取可用的主题列表
        返回: 包含主题信息的字典列表
        """
        try:
            themes = []
            if os.path.exists(cls.THEME_DIR):
                for dir_name in os.listdir(cls.THEME_DIR):
                    theme_path = os.path.join(cls.THEME_DIR, dir_name)
                    if os.path.isdir(theme_path):
                        config_path = os.path.join(theme_path,
                                                   'themeconfig.json')
                        settings_path = os.path.join(theme_path,
                                                     'themesettings.json')
                        img_path = os.path.join(theme_path, 'theme.jpg')

                        if os.path.isfile(config_path) and os.path.isfile(
                                img_path):
                            try:
                                with open(config_path, 'r',
                                          encoding='utf-8') as f:
                                    config_data = json.load(f)

                                # 读取主题设置
                                theme_settings = []
                                if os.path.isfile(settings_path):
                                    with open(settings_path,
                                              'r',
                                              encoding='utf-8') as sf:
                                        settings_data = json.load(sf)
                                        theme_settings = settings_data.get(
                                            'settings', [])

                                themes.append({
                                    'dirname':
                                    dir_name,
                                    'name':
                                    config_data.get('name',
                                                    _('未知主题')),  # 翻译默认值
                                    'author':
                                    config_data.get('author', _('未知作者')),
                                    'version':
                                    config_data.get('version', '1.0'),
                                    'description':
                                    config_data.get('description', ''),
                                    'main':
                                    config_data.get('main', ''),
                                    'settings':
                                    theme_settings,
                                    'preview':
                                    f'{dir_name}/theme.jpg'
                                })
                            except (json.JSONDecodeError, KeyError,
                                    FileNotFoundError) as e:
                                print(
                                    _('解析主题配置失败 {dir_name}: {error}').format(
                                        dir_name=dir_name, error=e))
                                continue
            # 收集静态文件
            call_command('collectstatic', '--noinput')
            return themes
        except Exception as e:
            print(_('获取主题列表错误:'), e)
            return []

    def save(self, *args, **kwargs):
        # 检查是否已存在实例
        # if self.__class__.objects.exists() and not self.pk:
        #     # 如果已经存在实例且当前实例没有主键（即新建实例）
        #     raise ValidationError(f"只能创建一个{self._meta.verbose_name}实例")
        self.pk = 1
        return super().save(*args, **kwargs)
