from django.shortcuts import render, redirect
import random
from django.contrib.auth import authenticate, login
from .forms import *
from Device .forms import DevicesForm
from django.db import IntegrityError
from django.conf import settings
from .models import*
from django.http import HttpResponse
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.contrib import messages
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.contrib.auth import logout
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import UserProfile
from Device .models import Devices
from .serializers import UserProfileSerializer, DeviceSerializer
from rest_framework.authtoken.models import Token
import os
#________________________________________________________Mail Functions____________________________________________

def tech4biz_generate_otp(length=6):
    otp = ""    
    for _ in range(length):
        otp += str(random.randint(0, 9))
    return otp

def tech4biz_send_otp_email(email):    
    otp = tech4biz_generate_otp()
    subject = 'Your OTP for Signup'
    html_content = render_to_string('accounts/otp_template.html', {'otp': otp})
    text_content = strip_tags(html_content)
    email_message = EmailMultiAlternatives(subject, text_content, settings.EMAIL_HOST_USER, [email])
    email_message.attach_alternative(html_content, "text/html")
    try:
        email_message.send()
        return otp
    except Exception as e:
        return None
    
#________________________________________________________Signup Login___________________________________________________

# def tech4biz_Signup(request):
#     if request.method == 'POST':
#         form = SignUpForm(request.POST)
#         if form.is_valid():
#             request.session['form_data'] = form.cleaned_data
#             email = form.cleaned_data['email']
#             try:
#                 otp = tech4biz_send_otp_email(email)
#                 print(otp)
#                 request.session['sent_otp'] = otp
#                 return redirect('otp_verification')
#             except Exception as e:
#                 return HttpResponse(f'Failed to send OTP email: {e}')
#     else:
#         form = SignUpForm()
#     return render(request, 'accounts/signup.html', {'form': form})



# def tech4biz_Signup(request):
#     if request.method == 'POST':
#         form = SignUpForm(request.POST)
#         if form.is_valid():
#             user_profile = form.save()  # Saves both the user and user profile
#             request.session['user_id'] = user_profile.user.id  # Assuming user_profile has a related User object
            
#             return JsonResponse({
#                 "message": "User registered successfully",
#                 "user_id": user_profile.user.id  # Include user.id in the response
#             }, status=200)
#         else:
#             # Return a more user-friendly error message
#             error_messages = form.errors.as_json()  # Get errors in JSON format
#             return JsonResponse({"error": error_messages}, status=400)  # Return form errors as JSON
#     else:
#         form = SignUpForm()  # Instantiate an empty form

#     return render(request, 'accounts/signup.html', {'form': form})
def tech4biz_Signup(request):
    mapbox_access_token = 'pk.eyJ1IjoiZmxleHhvbiIsImEiOiJjbHVtYzNoM2cwNXI2MnFveW51c2tyejVwIn0.ceqt6Ot6nU67CUmxVAWPEQ'
    print("Received a request to tech4biz_Signup")
    
    if request.method == 'POST':
        print("Processing POST request")
        
        form = SignUpForm(request.POST)
        device_form = DevicesForm(request.POST)

        print("SignUpForm and DevicesForm created")

        if form.is_valid():
            # Save the user profile from SignUpForm
            user_profile = form.save()
            print("User profile created:", user_profile)
            user_id = user_profile.user.id  # Access the ID of the newly created user from user_profile
            print("Extracted user ID:", user_id)
            
            # Set the user_id in the session
            request.session['user_id'] = user_id
            # Set 'used_by' field directly in device_form's data before validation
            device_form.data = device_form.data.copy()
            device_form.data['used_by'] = user_profile
            if device_form.is_valid():
                # Create device instance from device_form without saving it yet
                device_instance = device_form.save(commit=False)
                device_instance.used_by = user_profile # Set the user as 'used_by'
                
                print('Device instance prepared for saving:', device_instance)
                try:
                    # Save the device instance
                    device_instance.save()
                    print("Device instance saved successfully")
                    # Set the device ID in environment variable
                    os.environ['DEVICE_ID'] = str(device_instance.id)
                    print("Device ID set in OS environment:", os.environ['DEVICE_ID'])

                    device_id = device_instance.id
                    
                    return JsonResponse({
                        "message": "User and device registered successfully",
                        "user_id": user_profile.user.id,
                        "device_id": device_id 
                    }, status=200)
                except IntegrityError as e:
                    error_message = str(e)
                    print("IntegrityError occurred:", error_message)
                    form.add_error(None, error_message)
                    device_form.add_error(None, error_message)
            else:
                # Print device form errors if it is not valid
                print("Device form errors:", device_form.errors)
                return JsonResponse({
                    "device_errors": device_form.errors.as_json()
                }, status=400)
        else:
            # Return form errors if any exist
            error_messages = form.errors.as_json()
            device_error_messages = device_form.errors.as_json()
            print("Form errors:", error_messages)
            print("Device form errors:", device_error_messages)
            return JsonResponse({
                "error": error_messages,
                "device_errors": device_error_messages
            }, status=400)
    else:
        print("Request method is not POST")
        form = SignUpForm()
        device_form = DevicesForm()

    return render(request, 'accounts/signup.html', {
        'form': form,
        'device_form': device_form,
        "mapbox_access_token": mapbox_access_token
    })

def otp_verification(request):
    if request.method == 'POST':
        # Get individual OTP digits
        entered_otp1 = request.POST.get('email_otp1')
        entered_otp2 = request.POST.get('email_otp2')
        entered_otp3 = request.POST.get('email_otp3')
        entered_otp4 = request.POST.get('email_otp4')
        entered_otp5 = request.POST.get('email_otp5')
        entered_otp6 = request.POST.get('email_otp6')

        # Combine OTP digits into a single string
        entered_otp = entered_otp1 + entered_otp2 + entered_otp3 + entered_otp4 + entered_otp5 + entered_otp6
        
        print(entered_otp, "otp")  # Just for debugging

        stored_otp = request.session.get('sent_otp')

        if entered_otp == stored_otp:
            form_data = request.session.get('form_data')
            form = SignUpForm(form_data)
            if form.is_valid():
                form.save()
                del request.session['form_data']
                del request.session['sent_otp']
                return redirect('login')
            else:
                messages.error(request, 'Form data is not valid.')
                return redirect('signup')
        else:
            messages.error(request, 'Invalid OTP. Please try again.')
            return redirect('otp_verification')

    return render(request, 'accounts/otp_verification.html')

@csrf_exempt
def tech4biz_Login(request):
    if request.user.is_authenticated:  # Check if the user is already logged in
        return redirect('home')
    if request.method == 'POST':
        form = UserLoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            user = authenticate(request, username=email, password=password)
            if user is not None:
                login(request, user)
                return redirect('home')  
            else:
                return render(request, 'accounts/login.html', {'form': form, 'invalid_login': True})
    else:
        form = UserLoginForm()
    return render(request, 'accounts/login.html', {'form': form})


def user_logout(request):
    logout(request)
    return redirect('login')
    
def profile(request):
    return render(request, 'profile/profile.html')
#____________________________________________________________________________________________________________________

@api_view(['GET'])
@login_required  # Ensures the user is logged in
def get_user_details_and_device_pods(request):
    try:
        # Get the logged-in user's UserProfile
        user_profile = UserProfile.objects.get(user=request.user)

        # Get the devices associated with the logged-in user
        devices = Devices.objects.filter(used_by=user_profile)

        # Construct the response data
        response_data = {
            "user_details": {
                "user": user_profile.user.id,
                "email": user_profile.email,
                "phone_number": user_profile.phone_number,
                "company_name": user_profile.company_name,
            },
            "device_pods": [{"pod": device.pod} for device in devices]
        }
        print('response data',response_data)
        # Return data as JSON response
        return JsonResponse(response_data, status=200)
    
    except UserProfile.DoesNotExist:
        return JsonResponse({"error": "User profile not found."}, status=404)
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=500)
    




def tech4biz_loginwithAdd(request):
    mapbox_access_token = 'pk.eyJ1IjoiZmxleHhvbiIsImEiOiJjbHVtYzNoM2cwNXI2MnFveW51c2tyejVwIn0.ceqt6Ot6nU67CUmxVAWPEQ'
    print("Received a request inside")
    
    if request.method == 'POST':
        print("Processing POST request")
        
        form = UserForm(request.POST)
        device_form = DevicesForm(request.POST)

        print("UserForm and DevicesForm created")

        if form.is_valid():
            # Check if the user exists or create them if not
            email = form.cleaned_data['email']

            try:
                # Try to get the user based on the email
                user_profile = UserProfile.objects.get(user__email=email)
                print("User exists:", user_profile)
            except UserProfile.DoesNotExist:
                # If the user does not exist, create a new user
                print("Creating new user profile")
                user = User.objects.create_user(username=email, email=email)
                user_profile = UserProfile.objects.create(user=user)
                print("New user profile created:", user_profile)

            user_id = user_profile.user.id  # Access the ID of the user
            print("Extracted user ID:", user_id)
            
            # Set the user_id in the session
            request.session['user_id'] = user_id

            # Set 'used_by' field directly in device_form's data before validation
            device_form.data = device_form.data.copy()
            device_form.data['used_by'] = user_profile
            if device_form.is_valid():
                # Create device instance from device_form without saving it yet
                device_instance = device_form.save(commit=False)
                device_instance.used_by = user_profile  # Set the user as 'used_by'

                print('Device instance prepared for saving:', device_instance)
                try:
                    # Save the device instance
                    device_instance.save()
                    print("Device instance saved successfully")
                    # Set the device ID in the environment variable
                    os.environ['DEVICE_ID'] = str(device_instance.id)
                    print("Device ID set in OS environment:", os.environ['DEVICE_ID'])

                    device_id = device_instance.id

                    return JsonResponse({
                        "message": "User and device registered successfully",
                        "user_id": user_profile.user.id,
                        "device_id": device_id 
                    }, status=200)
                except IntegrityError as e:
                    error_message = str(e)
                    print("IntegrityError occurred:", error_message)
                    form.add_error(None, error_message)
                    device_form.add_error(None, error_message)
            else:
                # Print device form errors if it is not valid
                print("Device form errors:", device_form.errors)
                return JsonResponse({
                    "device_errors": device_form.errors.as_json()
                }, status=400)
        else:
            # Return form errors if any exist
            error_messages = form.errors.as_json()
            device_error_messages = device_form.errors.as_json()
            print("Form errors:", error_messages)
            print("Device form errors:", device_error_messages)
            return JsonResponse({
                "error": error_messages,
                "device_errors": device_error_messages
            }, status=400)
    else:
        print("Request method is not POST")
        form = UserForm()
        device_form = DevicesForm()

    return render(request, 'accounts/loginwithAdd.html', {
        'form': form,
        'device_form': device_form,
        "mapbox_access_token": mapbox_access_token
    })
