import logging
from django.shortcuts import render,redirect
from rest_framework.decorators import api_view
from .serializers import UserRegistrationSerializer,UserLoginSerializer,LoginLogSerializers,PersonalInfoSerializers,ProductMaterialSerializers,CigarProductSerializers,UserCustomizationSerializers
from rest_framework.response import Response
from django.http import JsonResponse
from rest_framework import status
from .models import User,ProductMaterial,UserCustomization,CigarProduct,LoginLog
from django.utils import timezone



logger = logging.getLogger(__name__)
def index(request):
	return render(request,'index.html')

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

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

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

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

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



# Add,Update,Delete operation of User
@api_view(['POST'])
def user_registration(request):
    try:
        data = request.data
        password = data.get('PASSWORD')
        confirm_password = data.get('CONFIRM_PASSWORD')

        if password != confirm_password:
            error_message = 'Password and Confirm Password do not match.'
            logger.warning(error_message)
            return Response({'error': error_message}, status=status.HTTP_400_BAD_REQUEST)
        serializer = UserRegistrationSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            success_message = 'User registered successfully.'
            logger.info(success_message)
            return Response({'message': success_message}, status=status.HTTP_201_CREATED)
        error_message = 'User registration failed. Invalid data.'
        logger.warning(error_message)
        return Response({'error': error_message}, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        logger.exception('An unexpected error occurred during user registration.')
        return Response({'error': 'Internal Server Error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    


@api_view(['POST'])
def user_login(request):
    try:
        serializer = UserLoginSerializer(data=request.data)
        if serializer.is_valid(): 
            user = serializer.validated_data
            if user:
                first_user_id = user.first().id
                user_instance = User.objects.get(id=first_user_id)
                x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '') 
                if x_forwarded_for:
                 ip = x_forwarded_for.split(',')[0]
                else:                                   
                 ip = request.META.get('REMOTE_ADDR')

                if request.session.session_key is None:
                 request.session.create()

                request.session['is_authenticated'] = True
                request.session['SESSION_ID'] = request.session.session_key
                request.session['LOGIN_ID'] = first_user_id
                request.session['NAME'] = user.first().NAME

                login_time = timezone.now()
                
                LoginLog.objects.create(
                            USER = user_instance,
                            LOGIN_DATETIME = login_time,
                            LOGIN_SESSION = request.session['SESSION_ID'],
                            IP_ADDRESS = ip,
                        )
                return Response({'message': 'Login successful.'}, status=status.HTTP_200_OK)
            else:
                return Response({'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)

        return Response({'error': 'Invalid data'}, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:
        logger.exception(e)
        print(e)

def user_logout(request):
    try:
        print("view1333")
        if LoginLog.objects.filter(LOGIN_SESSION=request.session['SESSION_ID']).exists():
            login = LoginLog.objects.filter(LOGIN_SESSION=request.session['SESSION_ID']).last()
            print("view11")
            LoginLog.objects.update(LOGIN_STATUS=False)
            login.LOGOUT_DATETIME = timezone.now()
            login.LOGIN_STATUS=False
            login.save()
            request.session.flush()
            print("view1")
            return redirect("index")
        else:
            request.session.flush()
            print("view3")
            return redirect("index")
    except Exception as e:
        request.session.flush()
        logger.exception(e)
        print("view2")
        return redirect("index")
        
@api_view(['GET'])
def get_personal_info_api(request, pk):
    try:
        user = User.objects.get(pk=pk)
        data = {
            'id': user.id,
            'NAME': user.NAME, 
            'EMAIL_ID': user.EMAIL_ID,
            'MOBILE_NO': user.MOBILE_NO,
        }
        return JsonResponse(data, status=status.HTTP_200_OK)
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# Add,Edit,Delete,Update for Product Material
@api_view(['POST'])
def add_product_material(request):
    try:
        serializer = ProductMaterialSerializers(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'message': 'Product Material Added SuccessFully'},serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# load All Product Material
@api_view(['GET'])
def load_product_material(request):
    try:
        material = ProductMaterial.objects.all()
        serializer = ProductMaterialSerializers(material, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['PUT'])
def update_product_material(request, pk):
    try:
        material = ProductMaterial.objects.get(pk=pk)
        if material:
            serializer = ProductMaterialSerializers(material, data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response({'message': 'Product Material Updated SuccessFully'},serializer.data)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        elif material.DoesNotExist:
            return Response({'message': 'Product Material Not Found'},status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['DELETE'])
def delete_product_material(request,pk):
    try:
        material = ProductMaterial.objects.get(pk=pk)
        if material:
            material.IS_DELETED = True
            material.save()
            return Response({'message': 'Product Material Deleted SuccessFully'},status=status.HTTP_204_NO_CONTENT)
        elif material.DoesNotExist:
            return Response({'message': 'Product Material Not Found'},status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# Add,Edit,Delete,load cigarProduct
@api_view(['POST'])
def add_cigar_product(request):
    try:
        serializer = CigarProductSerializers(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'message': 'Cigar Product Added SuccessFully'},serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['PUT'])
def update_cigar_product(request, pk):
    try:
        product = CigarProduct.objects.get(pk=pk)
        if product :
            serializer = CigarProductSerializers(product, data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response({'message': 'Cigar Product updated SuccessFully'},serializer.data)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        elif product.DoesNotExist:
            return Response({'message': 'Cigar Product Not Found'},status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['DELETE'])
def delete_cigar_product(request,pk):
    try:
        product = CigarProduct.objects.get(pk=pk)
        if product:
            product.IS_DELETED = True
            product.save()
            return Response({'message': 'Cigar Product Deleted SuccessFully'},status=status.HTTP_204_NO_CONTENT)
        elif User.DoesNotExist:
            return Response({'message': 'Cigar Product Not Found'},status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 


@api_view(['GET'])
def load_cigar_product_id(request,pk):
    try:
        cigar_product = get_object_or_404(CigarProduct, pk=pk)
        serializer = CigarProductSerializer(cigar_product)
        return Response(serializer.data, status=status.HTTP_200_OK)
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
 

@api_view(['GET'])
def load_cigar_product(request):
    try:
        material = CigarProduct.objects.all()
        serializer = CigarProductSerializers(material, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
 

# Add,Edit,Delete and get by id operation for UserCustomization
@api_view(['POST'])
def add_user_customization(request):
    try:
        serializer = UserCustomizationSerializers(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'message': 'User Customization Added SuccessFully'},serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['PUT'])
def update_user_customization(request, pk):
    try:
        material = UserCustomization.objects.get(pk=pk)
        if material:
            serializer = UserCustomizationSerializers(material, data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response({'message': 'User Customization Updated SuccessFully'},serializer.data,status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        elif material.DoesNotExist:
            return Response({'message': 'Customization not found'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['DELETE'])
def delete_user_customization(request,pk):
    try:
        customize = UserCustomization.objects.get(pk=pk)
        if customize:
            customize.IS_DELETED = True
            customize.save()
            return Response({'message': 'Customization Deleted Successfully'}, status=status.HTTP_204_NO_CONTENT)
        elif customize.DoesNotExist:
            return Response({'message': 'Customization not found'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
def load_user_customization_id(request, pk):
    try:
        customize = UserCustomization.objects.get(pk=pk)
        if customize:
            serializer = UserCustomizationSerializers(customize)
            return Response({data : serializer.data}, status=status.HTTP_200_OK)
        elif customize.DoesNotExist:
            return Response({'message': 'Customization not found'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        logger.exception(e)
        return Response({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# Add,Edit,Delete and get by id operation for UserCustomization
@api_view(['POST'])
def add_product_image(request):
    try:
        image = ProductImageSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'message': 'Product image Added SuccessFully'},serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['PUT'])
def update_product_image(request, pk):
    try:
        image = Product_Image.objects.get(pk=pk)
        if image:
            image = ProductImageSerializer(image, data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response({'message': 'Product image Updated SuccessFully'},serializer.data,status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        elif image.DoesNotExist:
            return Response({'message': 'Product image not found'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['DELETE'])
def delete_product_image(request,pk):
    try:
        image = Product_Image.objects.get(pk=pk)
        if image:
            image.IS_DELETED = True
            image.save()
            return Response({'message': ' Product image Deleted Successfully'}, status=status.HTTP_204_NO_CONTENT)
        elif image.DoesNotExist:
            return Response({'message': 'Product image not found'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        logger.exception(e)
        return JsonResponse({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
def load_product_image_id(request, pk):
    try:
        image = Product_Image.objects.get(pk=pk)
        if image:
            serializer = ProductImageSerializer(image)
            return Response({data : serializer.data}, status=status.HTTP_200_OK)
        elif image.DoesNotExist:
            return Response({'message': 'Product image not found'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        logger.exception(e)
        return Response({'detail': 'An error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)








# @api_view(['PUT'])
# def user_update(request, pk):
#     try:
#         user = User.objects.get(pk=pk)
#         if user:
#             serializer = UserRegistrationSerializer(user, data=request.data)
#             if serializer.is_valid():
#                 serializer.save()
#                 return Response(serializer.data)
#             return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#         elif user.DoesNotExist:
#             return Response({'message': 'User not Exist'},status=status.HTTP_404_NOT_FOUND)
#     except :
#         pass
            
# @api_view(['DELETE'])
# def user_delete(request,pk):
#     try:
#         user = User.objects.get(pk=pk)
#         if user:
#             user.is_deleted = True
#             user.save()
#             return Response({'message': 'User Deleted Successfully'},status=status.HTTP_204_NO_CONTENT)
#         elif User.DoesNotExist:
#             return Response({'message': 'User not Exist'},status=status.HTTP_404_NOT_FOUND)
#     except:
#         pass   













    
