from user_agents import parse
from django.utils.timezone import now
from django.utils.timezone import now, timedelta
from regulations.models import SuspiciousLog

# Ambang batas request sebelum diblokir
MAX_REQUESTS = 100
TIME_WINDOW = timedelta(minutes=1)  # Dalam 1 menit

def check_suspicious_activity(ip):
    """Cek apakah IP ini harus diblokir."""
    recent_logs = SuspiciousLog.objects.filter(ip=ip, timestamp__gte=now()-TIME_WINDOW)
    
    if recent_logs.count() > MAX_REQUESTS:
        SuspiciousLog.objects.filter(ip=ip).update(blocked=True)
        return True  # IP sudah diblokir
    
    return False  # Masih aman

def detect_device(user_agent):
    parsed_ua = user_agent  # Tidak perlu parse lagi karena sudah berupa objek UserAgent
    if parsed_ua.is_mobile:
        return 'Mobile'
    elif parsed_ua.is_tablet:
        return 'Tablet'
    else:
        return 'Desktop'


def parse_and_save_uu_data(file_content):
    # Split the file content into lines
    lines = file_content.split('\n')

    # Initialize variables to store extracted information
    nomor_uu = None
    tahun_uu = None
    judul_uu = None
    tentang_uu = None

    # Iterate through each line to find the relevant information
    for line in lines:
        # Extract Nomor_UU
        if line.startswith('Nomor_UU:'):
            nomor_uu = line.split(':')[1].strip()

        # Extract Tahun_UU
        elif line.startswith('Tahun_UU:'):
            tahun_uu = line.split(':')[1].strip()

        # Extract Judul_UU
        elif line.startswith('Judul_UU:'):
            judul_uu = line.split(':')[1].strip()

        # Extract Tentang_UU
        elif line.startswith('Tentang_UU:'):
            tentang_uu = line.split(':')[1].strip()

    # Check if required information is present
    if nomor_uu and tahun_uu and judul_uu and tentang_uu:
        # Save the information to the database or perform further processing
        # Example: UU.objects.create(Nomor_UU=nomor_uu, Tahun_UU=tahun_uu, Judul_UU=judul_uu, Tentang_UU=tentang_uu)
        pass
    else:
        # Raise a ValueError if required information is missing
        raise ValueError("Nomor_UU, Tahun_UU, Judul_UU, and Tentang_UU must be present in the file.")

# regulations/utils.py
def get_client_ip(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

from .utils import clean_search_query


import re

def clean_search_query(query):
    """Bersihkan query dari simbol dan spasi berlebihan"""
    cleaned = re.sub(r'[^\w\s]', '', query)  # hapus karakter aneh
    cleaned = re.sub(r'\s+', ' ', cleaned).strip()
    return cleaned
