from django.shortcuts import render
from django.contrib.auth.decorators import login_required, user_passes_test
from .models import CourseAnalytics, InstructorAnalytics, StudentAnalytics
from schedule.models import Course, Lesson, LessonEnrollment
from instructor.models import Instructor
from student.models import Student
import json
from django.http import HttpResponse

def is_admin(user):
    return user.profile.user_type == 'admin'

@login_required
@user_passes_test(is_admin)
def analytics_dashboard(request):
    course_analytics = CourseAnalytics.objects.all()
    instructor_analytics = InstructorAnalytics.objects.all()
    student_analytics = StudentAnalytics.objects.all()
    
    return render(request, 'analytics/dashboard.html', {
        'course_analytics': course_analytics,
        'instructor_analytics': instructor_analytics,
        'student_analytics': student_analytics
    })

@login_required
@user_passes_test(is_admin)
def course_analytics(request):
    courses = Course.objects.all()
    analytics = CourseAnalytics.objects.filter(course__in=courses)
    return render(request, 'analytics/course_analytics.html', {
        'courses': courses,
        'analytics': analytics
    })

@login_required
@user_passes_test(is_admin)
def instructor_analytics(request):
    instructors = Instructor.objects.all()
    analytics = InstructorAnalytics.objects.filter(instructor__in=instructors)
    return render(request, 'analytics/instructor_analytics.html', {
        'instructors': instructors,
        'analytics': analytics
    })

@login_required
@user_passes_test(is_admin)
def student_analytics(request):
    students = Student.objects.all()
    analytics = StudentAnalytics.objects.filter(student__in=students)
    return render(request, 'analytics/student_analytics.html', {
        'students': students,
        'analytics': analytics
    })

@login_required
@user_passes_test(is_admin)
def generate_reports(request):
    # Здесь будет логика генерации отчетов
    return render(request, 'analytics/reports.html')

@login_required
@user_passes_test(is_admin)
def export_data(request):
    data = {
        'courses': list(Course.objects.values()),
        'instructors': list(Instructor.objects.values()),
        'students': list(Student.objects.values()),
        'lessons': list(Lesson.objects.values()),
        'enrollments': list(LessonEnrollment.objects.values())
    }
    
    response = HttpResponse(
        json.dumps(data, ensure_ascii=False),
        content_type='application/json'
    )
    response['Content-Disposition'] = 'attachment; filename="analytics_data.json"'
    return response 