# views.py
from apps.content.models.download import Download
from apps.core.cache.static_cache import StaticCacheManager
from apps.core.models.static_settings import StaticSettings
from apps.core.utils.hash import unhash_id
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from django.utils.translation import gettext_lazy as _
from django.views.generic import DetailView


class DownloadDetailView(DetailView):
    model = Download

    def get_template_names(self):
        # theme = getattr(self.request, 'current_theme', 'default') template
        theme = settings.THEME_NAME
        #文章个性模板>栏目内容模板>主题模型内容页templates/articles/article_item.html
        #themes/default/templates/articles/article_item.html是最后的容灾收段
        templates = []
        if self.object.template:
            templates.append(
                self.object.template.replace(
                    f'{settings.BASE_DIR}/templates/themes/', ''))
        if self.object.category.content_template:
            templates.append(
                self.object.category.content_template.replace(
                    f'{settings.BASE_DIR}/templates/themes/', ''))
        model_name = self.object.category.content_type.model
        templates.extend([
            f"themes/{theme}/templates/item/{model_name}_item.html",
            "themes/default/templates/item/{model_name}_item.html"
        ])

        return templates

    def dispatch(self, request, *args, **kwargs):
        # 获取当前主题和备用模板路径
        theme = getattr(settings, 'THEME_NAME', 'default')
        templates = [
            f"themes/{theme}/templates/utils/403_restricted.html",
            "themes/default/templates/utils/403_restricted.html"
        ]
        # 先获取对象再校验权限
        self.object = self.get_object()
        if (self.object.staff_only or
                self.object.category.staff_only) and not request.user.is_staff:
            return render(request,
                          templates, {'message': '该内容仅限工作人员查看'},
                          status=403)
        if (self.object.allowed_groups.exists()
                and not self.object.allowed_groups.filter(
                    id__in=request.user.groups.all()).exists()) or (
                        self.object.category.allowed_groups.exists()
                        and not self.object.category.allowed_groups.filter(
                            id__in=request.user.groups.all()).exists()):
            return render(request,
                          templates, {'message': '您所在的用户组无权查看此内容'},
                          status=403)
        return super().dispatch(request, *args, **kwargs)

    def get_queryset(self):
        # 只允许已发布状态的内容
        return super().get_queryset().filter(
            status=Download.StatusChoices.REVIEW).select_related(
                'category', 'editor').prefetch_related('related_tags',
                                                       'related_wikis')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        obj = self.object
        context['obj'] = obj

        # 准备平台下载渠道
        platform_downloads = obj.platform_downloads.all()

        # 模板需要的附加数据
        context.update({
            'security_hashes': [
                (_('MD5校验码'), obj.md5_hash),
                (_('SHA256校验码'), obj.sha256_hash),
            ],
            'platform_downloads':
            platform_downloads,
            'support_platforms':
            obj.support_platforms.split(',') if obj.support_platforms else []
        })
        return context

    def get(self, request, *args, **kwargs):
        filename = request.path_info
        self.static_config = StaticSettings.get_solo()
        manager = StaticCacheManager(self.static_config.high_safe,
                                     self.static_config.static_item)
        self.object = self.get_object()
        # 获取静态内容

        if self.static_config.static_key:

            static_content = manager.get(filename)

            if static_content:
                return HttpResponse(static_content)

            # 执行父类get方法完成常规处理
        response = super().get(request, *args, **kwargs)
        if self.static_config.static_key:
            manager.create(filename, response.render().content.decode('utf-8'))

        return response

    def get_object(self, **kwargs):
        # 判断路径模式
        if 'pk' in self.kwargs:
            try:
                int(self.kwargs['pk'])
                return self._pk()
            except:
                return self._handle_hash()

        elif 'year' in self.kwargs:
            return self._validate_date_path()
        return super().get_object()

    def _pk(self):
        """pk查询逻辑"""
        obj_id = self.kwargs['pk']
        print(2222222)
        return get_object_or_404(Download, pk=int(obj_id), status=99)

    def _handle_hash(self):
        """哈希值查询逻辑"""
        return get_object_or_404(Download,
                                 pk=int(unhash_id(self.kwargs['pk'])),
                                 status=99)
