from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import EducationalMaterial
from users.models import Student, Teacher


@login_required
def material_list(request):
    """Список учебных материалов с фильтром по роли"""
    user = request.user

    # Определяем, какие материалы видны пользователю
    if user.role == 'student':
        student = user.student
        materials = EducationalMaterial.objects.filter(
            is_published=True,
            groups=student.group
        )
    elif user.role == 'teacher':
        teacher = user.teacher
        materials = EducationalMaterial.objects.filter(
            is_published=True
        )
    elif user.role == 'parent':
        parent = user.parent
        children = parent.children.all()
        materials = EducationalMaterial.objects.filter(
            is_published=True,
            groups__students__in=children
        ).distinct()
    else:
        materials = EducationalMaterial.objects.filter(is_published=True)

    # Фильтр по типу
    material_type = request.GET.get('type', '')
    if material_type:
        materials = materials.filter(material_type=material_type)

    material_types = EducationalMaterial.MATERIAL_TYPES

    context = {
        'materials': materials,
        'material_types': material_types,
        'current_type': material_type,
    }
    return render(request, 'materials/list.html', context)


@login_required
def material_detail(request, pk):
    """Детальный просмотр материала"""
    material = get_object_or_404(EducationalMaterial, pk=pk, is_published=True)

    # Проверка доступа
    user = request.user
    if user.role == 'student':
        if material.groups.exists() and user.student.group not in material.groups.all():
            return render(request, '403.html', status=403)

    context = {
        'material': material,
    }
    return render(request, 'materials/detail.html', context)