from django.http import FileResponse, Http404
from django.shortcuts import render, redirect, get_object_or_404
from django.utils import timezone
from datetime import timedelta
from django.core.exceptions import ValidationError
from django.contrib import messages
from .models import Clipboard


def validate_file_size(file):
    max_size_kb = 2500  # Limit to 2.5 mb
    max_size = max_size_kb * 1024
    if file.size > max_size:
        raise ValidationError(f"File too large. Size should not exceed {max_size_kb} KB.")

def catch_subpath(request, subpath=''):
    try:
        clipboard = Clipboard.objects.get(identifier=subpath)
        return render(request, 'clipboard_view.html', {
        'subpath': subpath, 
        'clipboard': clipboard
    })
    except Clipboard.DoesNotExist:
        return render(request, 'clipboard_create.html', {
        'subpath': subpath
    })
    
def download_file(request, identifier):
    clipboard = get_object_or_404(Clipboard, identifier=identifier)
    if not clipboard.file:
        raise Http404("No file exists.")

    response = FileResponse(clipboard.file.open('rb'), as_attachment=True, filename=clipboard.file.name)
    return response

def success(request):
    return render(request, 'success.html')

def home(request):
    return render(request, 'home.html')

def create_clip(request):
    if request.method == "POST":
        # Extract form data
        subpath = request.POST.get('subpath')
        content = request.POST.get('content')
        expiry_selection = request.POST.get('expiry')
        file = request.FILES.get('file_path')  # File is extracted from request.FILES

        # Check if the subpath already exists
        if Clipboard.objects.filter(identifier=subpath).exists():
            messages.error(request, "This route already exists. Please choose a different name.")
            return render(request, 'home.html')

        try:
            if file:   
                validate_file_size(file)
        except ValidationError as e:
            messages.error(request, e.message)  # Using Django messages to pass the error
            return render(request, 'clipboard_create.html', {
                'subpath': subpath,
                'content': content,
                'expiry': expiry_selection
            })

        # Calculate the expiry time
        now = timezone.now()
        if expiry_selection == '2min':
            expires_at = now + timedelta(minutes=2)
        elif expiry_selection == '5min':
            expires_at = now + timedelta(minutes=5)
        elif expiry_selection == '10min':
            expires_at = now + timedelta(minutes=10)
        elif expiry_selection == '30min':
            expires_at = now + timedelta(minutes=30)
        elif expiry_selection == '1hour':
            expires_at = now + timedelta(hours=1)
        elif expiry_selection == '6hour':
            expires_at = now + timedelta(hours=6)
        elif expiry_selection == '24hour':
            expires_at = now + timedelta(hours=24)
        else:
            # Handle the case where the expiry_selection is invalid
            return render(request, 'clipboard_create.html', {
                'subpath': subpath,
                'content': content,
                'expiry': expiry_selection
            })

        # Create a new Clipboard instance
        clip = Clipboard(
            identifier=subpath, 
            content=content,
            file=file,
            expires_at=expires_at
        )
        clip.save()

        return redirect('success', identifier=clip.identifier)
    else:
        return render(request, 'clipboard_create.html')

def success(request, identifier):
    return render(request, 'success.html', {'identifier': identifier})
