from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
import requests
import os
from django.views.decorators.csrf import csrf_exempt
from .models import *


# Create your views here.

def get_client_ip(request):
    client_ip = request.META.get('HTTP_X_FORWARDED_FOR', '').split(',')[0].strip() or request.META.get('REMOTE_ADDR', '')

    try:
        response = requests.get(f'http://ipinfo.io/{client_ip}/json')
        data = response.json()
        country = data.get('country', 'Unknown')
    except Exception as e:
        country = "Unknown"

    return JsonResponse({'ip': client_ip, 'country': country})


@csrf_exempt
def upload_file(request):
    if 'file' not in request.FILES or 'filename' not in request.POST:
        return JsonResponse({'data': 'Invalid Request'})

    file = request.FILES['file']
    fileName = request.POST['filename']
    path = os.path.join('static', 'images', 'uploaded_chat_files', fileName)

    # Ensure the directory exists
    os.makedirs(os.path.dirname(path), exist_ok=True)

    # If the file already exists, generate a new filename
    index = 1
    base_filename, extension = os.path.splitext(fileName)
    while os.path.exists(path):
        new_filename = f"{base_filename}_{index}{extension}"
        path = os.path.join('static', 'images', 'uploaded_chat_files', new_filename)
        index += 1

    # Write the entire file
    with open(path, 'wb+') as destination:
        destination.write(file.read())


    return JsonResponse({'data': 'Uploaded Successfully', 'existingPath': path})