from .models import PageView, Visitor
from django.utils import timezone
from django.db import transaction


class CSPMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response['Content-Security-Policy'] = "frame-ancestors 'self' https://metrika.yandex.ru https://metrika.yandex.by https://metrica.yandex.com https://metrica.yandex.com.tr https://*.webvisor.com"
        return response


class PageViewMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Игнорируем статические файлы и админку
        if not request.path.startswith('/static/') and not request.path.startswith('/admin/'):
            self.track_page_view(request)

        response = self.get_response(request)
        return response

    def track_page_view(self, request):
        try:
            with transaction.atomic():
                # Сохраняем просмотр страницы
                PageView.objects.create(
                    url=request.path,
                    ip_address=self.get_client_ip(request),
                    user_agent=request.META.get('HTTP_USER_AGENT', ''),
                    referer=request.META.get('HTTP_REFERER', '')
                )

                # Обновляем статистику посетителя
                ip = self.get_client_ip(request)
                visitor, created = Visitor.objects.get_or_create(
                    ip_address=ip,
                    defaults={
                        'first_visit': timezone.now(),
                        'last_visit': timezone.now()
                    }
                )

                if not created:
                    visitor.last_visit = timezone.now()
                    visitor.visit_count += 1
                    visitor.save()

        except Exception as e:
            # Логируем ошибку, но не прерываем выполнение
            print(f"Error tracking page view: {e}")

    def get_client_ip(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip