# Standard Library Imports

# Third-Party Library Imports

# Django Imports
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.hashers import make_password
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

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 and user['password'] == password:
                return render(request, 'welcome.html', {'email': email})  # Or redirect somewhere

        # 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, 'file_upload.html', {'email': email})

    return render(request, 'login.html')

        # Authenticate the user
    #     user = authenticate(request, username=email, password=password)

    #     if CustomUser.objects.filter(emailId=email).exists():
    #         print("User exists in database.")
        
    #     if user is not None:
    #         print("User authenticated successfully.")
    #         login(request, user)
    #         request.session['first_name'] = user.firstName
    #         request.session['full_name'] = str(user.firstName) + " " + str(user.lastName)
    #         request.session['role'] = user.get_role_display().title()
    #         request.session['joining_date'] = user.createdDate.strftime("%b, %Y")
    #         request.session['userId'] = user.userId
    #         return redirect('companies')
    #     else:
    #         print("Invalid credentials.")
    #         messages.error(request, "Invalid email or password.")
    #         return redirect('login_view')  # Redirect to login page if authentication fails
    # 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)
    messages.success(request, "You have been logged out successfully.")
    return redirect('login')



# index page
def index(request):
    return render(request, 'index.html')

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