# Standard Library Imports

# Third-Party Library Imports

# Django Imports
from django.contrib import messages
from .decorators import login_required
from django.http import JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings

from django.core.files.storage import FileSystemStorage

import os
import json

USER_DATA_FILE = os.path.join(settings.BASE_DIR, 'users.json')

# To login
def login_view(request):
    if request.method == "POST":
        email = request.POST.get("username")
        password = request.POST.get("password")
        print("Email: ", email)
        print("Password: ", password)

        # Check if file exists
        if os.path.exists(USER_DATA_FILE):
            with open(USER_DATA_FILE, 'r') as f:
                try:
                    users = json.load(f)
                except json.JSONDecodeError:
                    users = []
        else:
            users = []

        # Check if user already exists
        for user in users:
            if user['email'] == email:
                if user['password'] == password:
                    # login(request, user)
                    request.session['user_email'] = user['email']
                    # ✅ Correct credentials
                    return render(request, 'index.html', {'email': email})
                else:
                    # ❌ Wrong password
                    print("Invalid credentials.")
                    messages.error(request, "Invalid email or password.")
                    return redirect('login_view')
        # ❌ Email not found
        messages.error(request, "User not found.")
        return redirect('login_view')
        # If not found, save new user
        # users.append({'email': email, 'password': password})
        
        # with open(USER_DATA_FILE, 'w') as f:
        #     json.dump(users, f, indent=4)

        # return render(request, 'index.html', {'email': email})
    print("Rendering login page.")
    return render(request, 'login.html')


# To logout
@login_required
def logout_view(request):
    # Clear all the session data and log out the user
    # logout(request)
    if 'user_email' in request.session:
        request.session.flush()  # Clears all session data
        messages.success(request, "You have been logged out successfully.")
    return redirect('login_view')
    # messages.success(request, "You have been logged out successfully.")
    # return redirect('login')


# index page

# @login_required
# def upload(request):
#     if request.method == 'POST' and request.FILES.get('file'):
#         uploaded_file = request.FILES['file']
#         fs = FileSystemStorage()
#         filename = fs.save(uploaded_file.name, uploaded_file)
#         file_url = fs.url(filename)
#         return render(request, 'index.html', {'file_url': file_url, 'success': True})
#     return render(request, 'index.html')


@login_required
def upload(request):
    return render(request, 'index.html')

# get-data page
@login_required
def getData(request):
    return render(request, 'get-data.html')