import email
from django.shortcuts import render
from rest_framework import status,generics,permissions
from rest_framework.response import Response
from uritemplate import partial
from base.threads import LoginMailToUserThread, RegisterMailToUserThread, ResendOTPMailToUserThread,ContactMailToUserThread

from magazine.utils import send_login_to_user, send_mobile_otp_to_user,send_register_to_user
from .models import*
from .serializers import*
from magazineapp.models import*
from magazineapp.serializers import*
# from loguru import logger
import logging
logger = logging.getLogger(__name__)
from django.core import mail
# from rest_framework.permissions import AllowAny,IsAuthenticated
from rest_framework import generics, status, permissions
from rest_framework.permissions import IsAuthenticated
from django.conf import settings
from django.contrib.auth.hashers import make_password 
from django.db.models import Q
from .tests import generate_access_token
import jwt
from django.core.mail import send_mail
from django.core.mail import EmailMessage
import random,string,requests
from .base_message import*
from datetime import datetime, timedelta
from rest_framework.parsers import FormParser, MultiPartParser, FileUploadParser

# Create your views here.

# class CheckOtpView(generics.GenericAPIView):
#     serializer_class = CheckOtpViewSerializer

#     def post(self,request):
#         try:
#             request.data['phone_number'] = request.data.get('phone_number',None)
#             try:
#                 phone = request.data.get('phone_number',None)
#                 showdata = send_mobile_otp_to_user(phone, '2345')
#                 print(showdata,'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
#                 context = {'status': 1,'message':'dfsdfsdx.'}
#                 return Response(context, status=status.HTTP_201_CREATED)
#             except Exception as e:
#                 print(e)

            # print(request.data['phone_number'],'====')
            # if not request.data['phone_number']:
            #     context = {'status': 0,'message': 'Please enter phone number.'}
            #     return Response(context, status=status.HTTP_200_OK)
            # # userdata = User.objects.filter(phone_number=request.data['phone_number']).last()
            # send_mobile_otp_to_user(userdata.phone_number, userdata.otp)
            # # print(send_mobile_otp_to_user(userdata.phone_number, userdata.otp),'=====@@@@@!111')

            # serilaizer = self.serializer_class(data=request.data)
            # print('=====111')
            # if serilaizer.is_valid():
            #     print('======')
            #     userdata = User.objects.filter(phone_number=request.data['phone_number']).last()
            #     send_mobile_otp_to_user(userdata.phone_number, userdata.otp)

            #     context = {'status': 1, 'message': login_message['message'],'data':serilaizer.data}
            #     return Response(context, status=status.HTTP_200_OK)

            # context = {'status': 0,'message': serilaizer.errors}
            # return Response(context, status=status.HTTP_200_OK)
        # except Exception as e:
        #     logger.error('CheckOtpView:error => ' + str(e))
        #     context = {'status': 0, 'message': Exp_MESSAGE['message'],'error':str(e)}
        #     return Response(context, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

# register page
import datetime
class UserRegisterAPIView(generics.GenericAPIView):
    serializer_class = UserRegisterSerializer
    # parser_classes = (FormParser, MultiPartParser)

    def post(self,request,pk=None, *args, **kwargs):

        try:

            # start = datetime.datetime.now().date()
            # end = datetime.datetime.now().date() + datetime.timedelta(days=1)
            # print(start,'===')
            # print(end,'======')
            # users = User.objects.filter(email_varification = False,phone_varification = False,end_date__gte=end).values_list('id')
            # User.objects.filter(id__in=users).delete()
            # breakpoint()

            data=request.data
            data['username']=data['email']
            data['email']=data['email']
            # data['profile_pic']=''//data.get('profile_pic') if data.get('profile_pic') else None
            data['profile_pic']=""
            country=data.get('country_code',None)
            country_name=data['country_name']
            countryobj = Country.objects.all().filter(country_code=country,name__iexact=country_name).last()
            data['country']=countryobj.id
            data['social_login_type']=data.get('social_login_type') if data.get('social_login_type') else None
            data['uid']=data.get('uid') if data.get('uid') else None
            data['roles']=5
            data['groups']=[0]
            data['user_permissions']=[]
            otp_range = 4
            otp = ''.join(random.choices(string.digits, k = otp_range))
            data['otp']=otp
            now = datetime.datetime.now()
            now_plus_10 = now + timedelta(minutes = 3)
            data['exp_otp_datetime']=now_plus_10

            userdata = User.objects.filter(Q(username__iexact=data['email'])|Q(phone_number=data['phone_number'])).last()


            if userdata:
                serializer = self.serializer_class(userdata,data=request.data,partial=True)
                if serializer.is_valid():
                    serializer.save()

                if userdata.email_varification == False and userdata.phone_varification == False:
                    if data['email']:
                        User.objects.filter(id=userdata.id).update(otp=otp,exp_otp_datetime=now_plus_10)
                        record_data = {'username':data['email'],'current_otp':otp, 'name':userdata.first_name}
                        RegisterMailToUserThread(record_data).start()
                        context = {'status': 1,'message':'Please check your gmail account.'}
                        
                    else:
                        
                        send_mobile_otp_to_user(data['phone_number'], otp)
                        context = {'status': 1,'message':'Please check your mobile inbox.'}
                    return Response(context, status=status.HTTP_201_CREATED)

                elif userdata.email_varification == 1 and userdata.phone_varification == 1:
                    context = {'status': 0,'message':'You have already registered. Please login.',}
                    return Response(context, status=status.HTTP_201_CREATED)  

            else:
                # if userdata.email_varification == True or userdata.phone_varification == True:
                #     if data['email']:
                #         context = {'status': 1,'message':'Please check your gmail account.'}
                #         return Response(context, status=status.HTTP_201_CREATED)
                
                serializer = self.serializer_class(data=request.data)
                if serializer.is_valid():
                    magid = serializer.save()
                    mgview = User.objects.filter(id=magid.id).last()
                    serializers_views = RegisterSerializer(mgview)
                    users = User.objects.filter(username=serializer.data.get('username',None)).last()
                    # if data['phone_number']:
                    #     print('phone number varification data ')
                    #     send_mobile_otp_to_user(data['phone_number'], otp)
                    if data['email']:
                        print('email varification data')
                    # if data['phone_number']:
                    #     send_mobile_otp_to_user(data['phone_number'], otp)
                        User.objects.filter(id=users.id).update(otp=otp,exp_otp_datetime=now_plus_10)
                        record_data = {'username':data['email'],'current_otp':otp, 'name':users.first_name}
                        RegisterMailToUserThread(record_data).start()
                    else:
                        User.objects.filter(id=users.id).update(otp=otp,exp_otp_datetime=now_plus_10)
                        send_mobile_otp_to_user(data['phone_number'], otp)
                    
                    context = {'status': 1,'message': register_message['message'],'data':serializers_views.data}
                    return Response(context, status=status.HTTP_201_CREATED)
                context = {'status': 0,'message':serializer.errors,'data': serializer.errors}
                return Response(context, status=status.HTTP_201_CREATED)
                
        except Exception as e:
            logger.error('UserRegisterAPIView:error => ' + str(e))
            context = {'status': 0, 'message': "User registation has not allowed in your country ",'error':str(e)}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)


# server otp varification
import datetime

class verifyOTPView(generics.GenericAPIView):
    serializer_class = UserOTPVerifiySerializer

    def post(self,request):
        try:
            request.data['otp']=request.data['otp'] if request.data['otp'] else None
            if not request.data['otp']:
                context = {'status': 0,'message': 'Please enter otp.'}
                return Response(context, status=status.HTTP_200_OK)

            serilaizer = self.serializer_class(data=request.data)

            if serilaizer.is_valid():
                user=User.objects.filter(Q(username=request.data['username'])|Q(phone_number=request.data['username'])|Q(email=request.data['username'])).last()
                if not user:
                    context = {'status': 0,'message': 'Username is invalid'}
                    return Response(context, status=status.HTTP_200_OK)

                ################## for live server upload this code said that pradeep sir
                if user.email=='testingg@gmail.com':
                    if user.otp == request.data['otp'] or request.data['otp'] == '1111' :
                        expir_otp_time = user.exp_otp_datetime
                        current_datetime= datetime.datetime.now()
                        ### Check Expiry Data time for OTP.
                        if current_datetime < expir_otp_time:

                            access_token = generate_access_token(user.id)
                            User.objects.filter(id=user.id).update(email_varification=True,phone_varification=True)
                            user=User.objects.filter(Q(username=request.data['username'])|Q(phone_number=request.data['username'])|Q(email=request.data['username'])).last()
                            serializer=UserLoginSerializer(user)
                            context = {'status': 1,'message': 'OTP verify Success','access_token':access_token,'data':serializer.data}
                            return Response(context, status=status.HTTP_200_OK) 
                        else:
                            context = {'status': 0,'message': 'OTP has been expired.'}
                            return Response(context, status=status.HTTP_200_OK)

                    elif user.otp == request.data['otp']:
                        expir_otp_time = user.exp_otp_datetime
                        current_datetime= datetime.datetime.now()
                        ### Check Expiry Data time for OTP.
                        if current_datetime < expir_otp_time:

                            access_token = generate_access_token(user.id)
                            User.objects.filter(id=user.id).update(email_varification=True,phone_varification=True)
                            user=User.objects.filter(Q(username=request.data['username'])|Q(phone_number=request.data['username'])|Q(email=request.data['username'])).last()
                            serializer=UserLoginSerializer(user)
                            context = {'status': 1,'message': 'OTP verify Success','access_token':access_token,'data':serializer.data}
                            return Response(context, status=status.HTTP_200_OK) 
                        else:
                            context = {'status': 0,'message': 'OTP has been expired.'}
                            return Response(context, status=status.HTTP_200_OK)
                    else:
                        context = {'status': 0,'message': 'OTP is invalid'}
                        return Response(context, status=status.HTTP_200_OK)
                ################

                # if user.otp == request.data['otp'] or request.data['otp'] == '1111' :
                if user.otp == request.data['otp']:
                    expir_otp_time = user.exp_otp_datetime
                    current_datetime= datetime.datetime.now()
                    ### Check Expiry Data time for OTP.
                    if current_datetime < expir_otp_time:

                        access_token = generate_access_token(user.id)
                        User.objects.filter(id=user.id).update(email_varification=True,phone_varification=True)
                        user=User.objects.filter(Q(username=request.data['username'])|Q(phone_number=request.data['username'])|Q(email=request.data['username'])).last()
                        serializer=UserLoginSerializer(user)
                        context = {'status': 1,'message': 'OTP verify Success','access_token':access_token,'data':serializer.data}
                        return Response(context, status=status.HTTP_200_OK) 
                    else:
                        context = {'status': 0,'message': 'OTP has been expired.'}
                        return Response(context, status=status.HTTP_200_OK)
                else:
                    context = {'status': 0,'message': 'OTP is invalid'}
                    return Response(context, status=status.HTTP_200_OK)
            else:
                context = {'status': 0,'message': 'OTP or Username Invalid'}
                return Response(context, status=status.HTTP_200_OK)
        except Exception as e:
            logger.error('UserLoginAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message'],'error':str(e)}
            return Response(context, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# class verifyOTPView(generics.GenericAPIView):
#     serializer_class = UserLoginSerializer
#     def post(self, request):
#         username = request.data.get('username')
#         otp = request.data.get('otp')
#         try:
#             if username is None:
#                 context = {'status': 0,'message': 'Please enter correct username.'}
#                 return Response(context, status=status.HTTP_201_CREATED)
#             if otp is None:
#                 context = {'status': 0,'message': 'Please enter correct otp.'}
#                 return Response(context, status=status.HTTP_201_CREATED)
#             exp_datetime=User.objects.filter(Q(username__iexact=username)|Q(phone_number=username)).last()
#             if exp_datetime is None:
#                 context = {'status': 0,'message': 'Please enter correct username.'}
#                 return Response(context, status=status.HTTP_201_CREATED)
#             otp_obj=User.objects.filter(otp=otp).last()
#             if str(otp_obj) is None:
#                 context = {'status': 0,'message': 'Please enter correct otp.'}
#                 return Response(context, status=status.HTTP_201_CREATED)
#             current_datetime= datetime.datetime.now()
#             # current_datetime = datetime.datetime.now()+datetime.timedelta(minutes=10)
#             users = User.objects.filter(Q(email=username)|Q(phone_number=username)).last() 
#             if users is None:
#                 context = {'status': 0,'message': 'Please enter correct username.'}
#                 return Response(context, status=status.HTTP_201_CREATED)
#             access_token = generate_access_token(users.id)
#             eddd = exp_datetime.exp_otp_datetime
#             # current_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
#             # expiry_date = datetime.datetime.strftime(exp_datetime.exp_otp_datetime, "%Y-%m-%d %H:%M:%S")
#             current_datetime = current_datetime
#             expiry_date =exp_datetime.exp_otp_datetime
            
#             if current_datetime < expiry_date:
#                 if int(exp_datetime.otp) == int(otp):
#                     exp_datetime.verified = True
#                     exp_datetime.save()

#                     user=User.objects.filter(Q(username__iexact=username)|Q(phone_number=username)).first()
#                     User.objects.filter(id=user.id).update(email_varification=True,phone_varification=True)

#                     serializer=self.serializer_class(users)
#                     context = {'status': 1,'message': 'OTP verify Success','access_token':access_token,'data':serializer.data}
#                     return Response(context, status=status.HTTP_201_CREATED)
#                 else:
#                     context = {'status': 0,'message': "OTP verify is fail"}
#                     return Response(context, status=status.HTTP_201_CREATED)
#             else:
#                 context = {'status': 0,'message':"Expire OTP"}
#                 return Response(context, status=status.HTTP_201_CREATED)
#         except Exception as e:
#             logger.error('UserLoginAPIView:error => ' + str(e))
#             context = {'status': 0, 'message': Exp_MESSAGE['message'],'error':str(e)}
#             return Response(context, status=status.HTTP_400_BAD_REQUEST)



# server LOGIN API View.# surya

class UserLoginAPIView(generics.GenericAPIView):
    serializer_class = UserLoginSerializer
    permission_classes = (permissions.AllowAny,)
 
    def post(self, request):
        try:
            
            update = {}
            username = request.data.get('username',None)
            device_id = request.data.get('device_id',None)
            fcm_token = request.data.get('fcm_token',None)
            country_code = request.data.get('country_code',None)
            country_sort_name = request.data.get('country_sort_name',None)
            

            if device_id:
                update['device_id'] = request.data.get('device_id',None)
            if fcm_token:
                update['fcm_token'] = request.data.get('fcm_token',None)

            if country_code:
                country = Country.objects.filter(Q(country_code__iexact = country_code)|Q(sortname__iexact = country_sort_name)).first()

                if country:
                    update['country'] = country.id
                else:
                    context = {'status': 0,'message': 'Please enter correct country code or country sort name.'}
                    return Response(context, status=status.HTTP_201_CREATED)

            user  = User.objects.filter(username__iexact = username) 
            phone = User.objects.filter(phone_number=username)

            code_valid = phone.filter(country_code = country_code) if phone else None   
            # print(user,"======", phone,"=====",username)
            # breakpoint()
            users = user.last() if user else phone.last()

            if not users: # and username.isdigit():
                # context = {'status': 0,'message': 'Please enter valid phone number.'}
                context = {'status': 0,'message': 'This user is not registered please sign up'}
                return Response(context, status=status.HTTP_201_CREATED)

            if phone and not code_valid: 
                context = {'status': 0,'message': 'Invalid country code. Please select valid country code.'}
                return Response(context, status=status.HTTP_201_CREATED)

            elif not users or not " ":
                context = {'status': 0,'message': 'Please enter valid username.'}
                return Response(context, status=status.HTTP_201_CREATED)

            if users:
                if update:
                    serializer = UserLoginSerializer(users,data=update, partial=True)
                    if serializer.is_valid():
                        serializer.save()
                    else:
                        print(serializer.errors,"=============================///")
                access_token = generate_access_token(users.id)
                otp_range = 4
                current_otp = ''.join(random.choices(string.digits, k = otp_range))
                current_datetime = datetime.datetime.now()+datetime.timedelta(minutes=3)
                User.objects.filter(Q(username__iexact = username)|Q(phone_number__iexact=username)).update(otp=current_otp,exp_otp_datetime = current_datetime)
                userdata = User.objects.filter(Q(username__iexact = username)|Q(phone_number__iexact=username)).last()
                # print(userdata.country_name,'====!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
                if user:

                    record_data = {'username':userdata.username,'current_otp':userdata.otp, 'name':userdata.first_name}
                    LoginMailToUserThread(record_data).start()

                    ######################
                    mysublist = MagazinePurchaseInfo.objects.filter(users=users.id,is_subscription=True).last()
                    serializer = UserSubscriptionListSerializer(mysublist) 
                    country = Country.objects.filter(Q(country_code__iexact = country_code)|Q(sortname__iexact = country_sort_name)).first()

                    address1= users.address if users.address else ""
                    address2= users.address_line_2 if users.address_line_2 else ""
                    state= users.state if users.state else ""
                    city= users.city if users.city else ""
                    # country_name = users.country_name if users.country_name else ""
                    country_name = users.country.name if users.country.name else ""
                    country_sortname = users.country.sortname if users.country.sortname else ""
                    # country_code = country.country_code if users.country.country_code else None
                    dicts={'id':users.id,'first_name':users.first_name,'last_name':users.last_name,'username':users.username,'phone_number':users.phone_number,'country_code':country_code,'device_id':users.device_id,'fcm_token':users.fcm_token,'otp':userdata.otp,'zipcode':users.zipcode,'address_line_1':address1,'address_line_2':address2,'state':state,'city':city,'country_name':country_name,'country_sortname':country_sortname,'Subscription_data':serializer.data}
                    context = {'status': 1, 'message': login_message['message'],"access_token": access_token,'data':dicts}
                    return Response(context, status=status.HTTP_200_OK)
                    ########################

                if phone:
                    userdata = User.objects.filter(phone_number__iexact=username).last()
                    send_mobile_otp_to_user(userdata.phone_number, userdata.otp)

                mysublist = MagazinePurchaseInfo.objects.filter(users=users.id,is_subscription=True).last()
                serializer = UserSubscriptionListSerializer(mysublist) 
                country = Country.objects.filter(Q(country_code__iexact = country_code)|Q(sortname__iexact = country_sort_name)).first()

                address1= users.address if users.address else ""
                address2= users.address_line_2 if users.address_line_2 else ""
                state= users.state if users.state else ""
                city= users.city if users.city else ""
                # country_name = users.country_name if users.country_name else ""
                country_name = users.country.name if users.country.name else ""
                country_sortname = users.country.sortname if users.country.sortname else ""
                dicts={'id':users.id,'first_name':users.first_name,'last_name':users.last_name,'username':users.username,'phone_number':users.phone_number,'country_code':country.country_code,'device_id':users.device_id,'fcm_token':users.fcm_token,'otp':userdata.otp,'zipcode':users.zipcode,'address_line_1':address1,'address_line_2':address2,'state':state,'city':city,'country_name':country_name,'country_sortname':country_sortname,'Subscription_data':serializer.data}
                context = {'status': 1, 'message': login_message['message'],"access_token": access_token,'data':dicts}
                return Response(context, status=status.HTTP_200_OK)
            else:
                context = {'status': 0,'message': 'Please enter correct username or phone number.'}
                return Response(context, status=status.HTTP_201_CREATED)

        except Exception as e:
            logger.error('UserLoginAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message'],'error':str(e)}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)




# # test  LOGIN API View.
# class UserLoginAPIView(generics.GenericAPIView):
#     serializer_class = UserLoginSerializer
#     permission_classes = (permissions.AllowAny,)
 
#     def post(self, request):
#         try:
            
#             update = {}
#             username = request.data.get('username',None)
#             device_id = request.data.get('device_id',None)
#             fcm_token = request.data.get('fcm_token',None)
#             country_code = request.data.get('country_code',None)
#             country_sort_name = request.data.get('country_sort_name',None)

#             if device_id:
#                 update['device_id'] = request.data.get('device_id',None)
#             if fcm_token:
#                 update['fcm_token'] = request.data.get('fcm_token',None)

#             if country_code:
#                 country = Country.objects.filter(Q(country_code__iexact = country_code)|Q(sortname__iexact = country_sort_name)).first()

#                 if country:
#                     update['country'] = country.id
#                 else:
#                     context = {'status': 0,'message': 'Please enter correct country code or country sort name.'}
#                     return Response(context, status=status.HTTP_201_CREATED)

#             user  = User.objects.filter(username__iexact = username)
#             phone = User.objects.filter(phone_number=username)

#             users = user.last() if user else phone.last()

#             if not users and username.isdigit():
#                 context = {'status': 0,'message': 'Please enter correct phone number.'}
#                 return Response(context, status=status.HTTP_201_CREATED)
#             elif not users:
#                 context = {'status': 0,'message': 'Please enter correct username.'}
#                 return Response(context, status=status.HTTP_201_CREATED)

#             if users:
#                 if update:
#                     serializer = UserLoginSerializer(users,data=update, partial=True)
#                     if serializer.is_valid():
#                         serializer.save()
#                     else:
#                         print(serializer.errors,"=============================///")
#                 access_token = generate_access_token(users.id)
#                 otp_range = 4
#                 current_otp = ''.join(random.choices(string.digits, k = otp_range))
#                 current_datetime = datetime.datetime.now()+datetime.timedelta(minutes=3)
#                 User.objects.filter(Q(username__iexact = username)|Q(phone_number__iexact=username)).update(otp=current_otp,exp_otp_datetime = current_datetime)
#                 userdata = User.objects.filter(Q(username__iexact = username)|Q(phone_number__iexact=username)).last()
#                 if user:
#                     record_data = {'username':userdata.username,'current_otp':userdata.otp, 'name':userdata.first_name}
#                     LoginMailToUserThread(record_data).start()


#                 if phone:
#                     userdata = User.objects.filter(phone_number__iexact=username).last()
#                     send_mobile_otp_to_user(userdata.phone_number, userdata.otp)

#                 mysublist = MagazinePurchaseInfo.objects.filter(users=users.id,is_subscription=True).last()
#                 serializer = UserSubscriptionListSerializer(mysublist) 
#                 print(users.id,'======users.address')
#                 country = Country.objects.filter(Q(country_code__iexact = country_code)|Q(sortname__iexact = country_sort_name)).first()
#                 address1= users.address if users.address else ""
#                 address2= users.address_line_2 if users.address_line_2 else ""
#                 state= users.state if users.state else ""
#                 city= users.city if users.city else ""
#                 country_name = users.country_name if users.country_name else ""
#                 dicts={'id':users.id,'first_name':users.first_name,'last_name':users.last_name,'username':users.username,'phone_number':users.phone_number,'country_code':country.country_code,'device_id':users.device_id,'fcm_token':users.fcm_token,'otp':users.otp,'zipcode':users.zipcode,'address_line_1':address1,'address_line_2':address2,'state':state,'city':city,'country_name':country_name,'Subscription_data':serializer.data}
#                 context = {'status': 1, 'message': login_message['message'],"access_token": access_token,'data':dicts}
#                 return Response(context, status=status.HTTP_200_OK)

#             else:

#                 context = {'status': 0,'message': 'Please enter correct username or phone number.'}
#                 return Response(context, status=status.HTTP_201_CREATED)

#         except Exception as e:
#             logger.error('UserLoginAPIView:error => ' + str(e))
#             context = {'status': 0, 'message': Exp_MESSAGE['message'],'error':str(e)}
#             return Response(context, status=status.HTTP_400_BAD_REQUEST)

# # Test Social Login
# class SocialLoginAPIView(generics.GenericAPIView):
#     # parser_classes = (FormParser, MultiPartParser)
#     serializer_class = SocialLoginSerializer
#     # permission_classes = (permissions.AllowAny,)
    
 
#     def post(self, request):
#         try:
#             username = request.data.get('username',None)
#             uid = request.data.get('uid',None)
#             first_name = request.data.get('first_name',None)
#             profile_pic = request.data.get('profile_pic',None)
#             response = Response()
#             if not uid:
#                 context = {'status': 0,'message': 'Please enter id.'}
#                 return Response(context, status=status.HTTP_200_OK)

#             country_code = request.data.get('country_code',None)
#             country_sort_name = request.data.get('country_sort_name',None)

#             country = Country.objects.filter(Q(country_code__iexact = country_code)|Q(sortname__iexact = country_sort_name)).first()
#             if not country:
#                 context = {'status': 0,'message': 'Please enter correct country code or country sort name.'}
#                 return Response(context, status=status.HTTP_201_CREATED)

#             users_obj = User.objects.filter(Q(username__iexact=username)|Q(uid__iexact=uid)).last()
#             if not users_obj:
#                 dic={'uid':uid,'first_name':first_name,'username':username}
#                 context = {'status': 2,'message': 'This user is not exist.','data':dic}
#                 return Response(context, status=status.HTTP_200_OK)
#             if users_obj:
#                 if username is None:
#                     context = {'status': 0,'message': 'Please enter correct username or uid.'}
#                     return Response(context, status=status.HTTP_200_OK)

#                 users = User.objects.filter(Q(username__iexact=username)|Q(uid__iexact=uid)).last()

#                 if(users is None):
#                     context = {'status': 0,'message': 'Please enter correct username or uid.'}
#                     return Response(context, status=status.HTTP_200_OK)
#                 users = User.objects.filter(Q(username__iexact=username)|Q(uid__iexact=uid)).last() 
#                 User.objects.filter(Q(username__iexact=username)|Q(uid__iexact=uid)).update(country_code=country.country_code)
#                 access_token = generate_access_token(users.id)
#                 serializer = self.serializer_class(users)
#                 response.data = {'status': 1, 'message': Social_login_message['message'],"access_token": access_token,'data':serializer.data}
#                 return response

#         except Exception as e:
#             logger.error('SocialLoginAPIView:error => ' + str(e))
#             context = {'status': 0, 'message': Exp_MESSAGE['message'],'error':str(e)}
#             return Response(context, status=status.HTTP_400_BAD_REQUEST)

# server Social Login
class SocialLoginAPIView(generics.GenericAPIView):
    serializer_class = SocialLoginSerializer
    # permission_classes = (permissions.AllowAny,)
    # parser_classes = (FormParser, MultiPartParser)
 
    def post(self, request):
        try:
            username = request.data.get('username',None)
            uid = request.data.get('uid',None)
            first_name = request.data.get('first_name',None)
            response = Response()
            # if not uid:
            #     context = {'status': 0,'message': 'Please enter id.'}
            #     return Response(context, status=status.HTTP_200_OK)

            users_obj = User.objects.filter(Q(username__iexact=username)|Q(uid__iexact=uid)).last()

            if not users_obj:
                dic={'uid':uid,'first_name':first_name,'username':username}
                context = {'status': 2,'message': 'This user is not exist.','data':dic}
                return Response(context, status=status.HTTP_200_OK)

            if username is None:
                context = {'status': 0,'message': 'Please enter correct username or uid.'}
                return Response(context, status=status.HTTP_200_OK)

            users = User.objects.filter(Q(username=username)|Q(uid__iexact=uid),Q(email_varification=False)|Q(phone_varification=False)).last()

            if users:
                context = {'status': 2,'message': 'You have already register please you go to login'}
                return Response(context, status=status.HTTP_200_OK)

            users = User.objects.filter(Q(username__iexact=username)|Q(uid__iexact=uid)).last() 
            access_token = generate_access_token(users.id)
            serializer = self.serializer_class(users)

            response.data = {'status': 1, 'message': Social_login_message['message'],"access_token": access_token,'access_key':'hiuohiuohiuh','data':serializer.data}
            return response

        except Exception as e:
            logger.error('SocialLoginAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message'],'error':str(e)}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)

# # Social Login
# class SocialLoginAPIView(generics.GenericAPIView):
#     serializer_class = SocialLoginSerializer
#     # permission_classes = (permissions.AllowAny,)
#     # parser_classes = (FormParser, MultiPartParser)
 
#     def post(self, request):
#         try:
#             username = request.data.get('username',None)
#             phone_number = request.data.get('phone_number',None)
#             response = Response()

#             if not username and not phone_number:
#                 context = {'status': 0,'message': 'Please enter username and phone number.'}
#                 return Response(context, status=status.HTTP_201_CREATED)

#             users_obj = User.objects.filter(Q(username__iexact=username)|Q(phone_number__iexact=username)).last()
#             if users_obj:
#                 if username is None:
#                     context = {'status': 0,'message': 'Please enter correct username or phone number.'}
#                     return Response(context, status=status.HTTP_201_CREATED)
#                 users = User.objects.filter(Q(username__iexact=username)|Q(phone_number__iexact=username)).last()
#                 if(users is None):
#                     context = {'status': 0,'message': 'Please enter correct username or phone number.'}
#                     return Response(context, status=status.HTTP_201_CREATED)
#                 # users = User.objects.filter(username__iexact=username).last()
#                 # users = User.objects.filter(Q(username__iexact=username,social_login_type=request.data.get('social_login_type',None))|Q(phone_number__iexact=username,social_login_type=request.data.get('social_login_type',None))).last() 
#                 users = User.objects.filter(Q(username__iexact=username)|Q(phone_number__iexact=username)).last() 
#                 access_token = generate_access_token(users.id)
#                 serializer = self.serializer_class(users)
#                 response.data = {'status': 1, 'message': Social_login_message['message'],"access_token": access_token,'data':serializer.data}
#                 return response

#             data=request.data.dict()
#             data['username']=data.get('username',None)
#             data['email']=data['username']
#             data['profile_pic']=data.get('profile_pic') if data.get('profile_pic') else None
#             country=data.get('country_code',None)
#             countryobj = Country.objects.all().filter(country_code=country).last()
#             data['country']=countryobj.id
#             data['roles']=5
#             data['groups']=[0]
#             data['user_permissions']=[]
#             otp_range = 4
#             otp = ''.join(random.choices(string.digits, k = otp_range))
#             data['otp']=otp
#             now = datetime.datetime.now()
#             now_plus_10 = now + timedelta(minutes = 3)
#             data['exp_otp_datetime']=now_plus_10

#             userdata = User.objects.filter(Q(username__iexact=data['email'])|Q(phone_number=data['phone_number'])).last()
#             if userdata:
#                 if userdata.email_varification == False and userdata.phone_varification == False:
#                     if data['email']:
#                         User.objects.filter(id=userdata.id).update(otp=otp,exp_otp_datetime=now_plus_10)
#                         record_data = {'username':data['email'],'current_otp':otp, 'name':userdata.first_name}
#                         RegisterMailToUserThread(record_data).start()
#                         context = {'status': 1,'message':'Please check your gmail account.'}
#                     else:
#                         send_mobile_otp_to_user(data['phone_number'], otp)
#                         context = {'status': 1,'message':'Please check your mobile inbox.'}
#                     return Response(context, status=status.HTTP_201_CREATED)

#                 elif userdata.email_varification == True or userdata.phone_varification == True:
#                     context = {'status': 0,'message':'You have already registered. Please login.',}
#                     return Response(context, status=status.HTTP_201_CREATED)   

#             else:

#                 serializer = SocialRegisterSerializer(data=data)
#                 if serializer.is_valid():
#                     serializer.save()
#                     users = User.objects.filter(username=serializer.data.get('username',None)).last()

#                     if data['email']:
#                         User.objects.filter(id=users.id).update(otp=otp,exp_otp_datetime=now_plus_10)
#                         record_data = {'username':data['email'],'current_otp':otp, 'name':users.first_name}
#                         RegisterMailToUserThread(record_data).start()
#                     else:
#                         User.objects.filter(id=users.id).update(otp=otp,exp_otp_datetime=now_plus_10)
#                         send_mobile_otp_to_user(data['phone_number'], otp)

#                     # dicts={'id':users.id,'first_name':users.first_name,'last_name':users.last_name,'username':users.username,'phone_number':users.phone_number,'country_code':countryobj.country_code,'device_id':users.device_id,'fcm_token':users.fcm_token,'otp':otp,'profile_pic':users.profile_pic,'social_login_type':users.social_login_type,'uid':users.id}
#                     context = {'status': 2,'message': social_register_message['message'],'data':serializer.data}
#                     # context = {'status': 2,'message': social_register_message['message'],'data':dicts}
#                     return Response(context, status=status.HTTP_201_CREATED)
#                 context = {'status': 0,'message':'This username is already exists.','data': serializer.errors}
#                 return Response(context, status=status.HTTP_201_CREATED)

#         except Exception as e:
#             logger.error('SocialLoginAPIView:error => ' + str(e))
#             context = {'status': 0, 'message': Exp_MESSAGE['message'],'error':str(e)}
#             return Response(context, status=status.HTTP_400_BAD_REQUEST)


#Resend Otp api
class ResendOtpAPIView(generics.GenericAPIView):
    serializer_class = SocialLoginSerializer
    permission_classes = (permissions.AllowAny,)
    def post(self, request):

        try:
            username = request.data.get('username',None)
            if username is None:
                context = {'status': 0,'message': 'Please enter correct username and phone number.'}
                return Response(context, status=status.HTTP_201_CREATED)
            users = User.objects.filter(Q(username__iexact=username)|Q(phone_number__iexact=username)).last()
            
            if(users is None):
                context = {'status': 0,'message': 'Please enter correct username and phone number.'}
                return Response(context, status=status.HTTP_201_CREATED)
            user_obj = User.objects.filter(username__iexact=username) 
            phone_obj = User.objects.filter(phone_number=username)

            if user_obj:
                otp_range = 4
                current_otp = ''.join(random.choices(string.digits, k = otp_range))
                current_datetime = datetime.datetime.now()+datetime.timedelta(minutes=3)
                users=User.objects.filter(username__iexact=username).update(otp=str(current_otp),exp_otp_datetime = current_datetime)
                userdata=User.objects.filter(username=username).last()

                record_data = {'username':userdata.username,'current_otp':userdata.otp, 'name':userdata.first_name}
                ResendOTPMailToUserThread(record_data).start()
                context = {'status': 1, 'message': resendotp_message['message'],'data':record_data}
                return Response(context, status=status.HTTP_200_OK)

            if phone_obj:
                otp_range = 4
                current_otp = ''.join(random.choices(string.digits, k = otp_range))
                current_datetime = datetime.datetime.now()+datetime.timedelta(minutes=3)
                users=User.objects.filter(phone_number=username).update(otp=str(current_otp),exp_otp_datetime = current_datetime)

                userdata=User.objects.filter(phone_number=username).values()
                ### OTP Send to User.
                send_mobile_otp_to_user(userdata[0]['phone_number'], userdata[0]['otp'])

                context = {'status': 1, 'message': resendotp_message['message']}
                return Response(context, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error('ResendOtpAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message'],'error':str(e)}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)


#show all data
class ShowdataAPIView(generics.GenericAPIView):
    serializer_class = UserRegisterSerializer
    # permission_classes = (permissions.IsAuthenticated,)
    # permission_classes = (IsAuthenticated,)
    def get(self, request,id=None):
        try:   
            if id is not None:
                
                users=User.objects.get(id=id)
                serializer = self.serializer_class(users,many=False)
                context = {'status': 1,'message': 'User Record found successfully.','data':serializer.data}
                return Response(context, status=status.HTTP_200_OK)
                
            users=User.objects.all()
            serializer = UserRegisterSerializer(users,many=True)
            context = {'status': 1,'message': 'User Record found successfully.','data':serializer.data}
            return Response(context, status=status.HTTP_200_OK)
        except Exception as e:
            logger.error('ShowdataAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message']}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)


# Country code api
class CountryAPIView(generics.GenericAPIView):
    queryset = Country.objects.all()
    serializer_class = CountrySerializer
    # pagination_class = StandardResultsSetPagination

    def post(self,request):
        try:
            for item in request.data['countries']:
                serializer = self.serializer_class(data=item,many=False)
                if serializer.is_valid():
                    serializer.save()
            context = {'status': 1,'message': 'Record Found Successful.',}
            return Response(context, status=status.HTTP_201_CREATED)

        except Exception as e:
            logger.error('CountryAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message']}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)

    def get(self,request):
        try:
            users=Country.objects.all()
            serializer = self.serializer_class(users,many=True)
            context = {'status': 1,'message': 'Record Found Successful.','data': serializer.data}
            return Response(context, status=status.HTTP_201_CREATED)
            
        except Exception as e:
            logger.error('CountryAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message']}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)


# Subscription api
class SubscriptionAPIView(generics.GenericAPIView):
    serializer_class = SubscriptionSerializer
    permission_classes = (permissions.IsAuthenticated,)
    # permission_classes = (IsAuthenticated,)
    def post(self,request):
        try:
            request.data['users']=request.data['user_id']
            serializer = self.serializer_class(data=request.data)
            if serializer.is_valid():
                serializer.save()
                context = {'status': 1,'message': 'Subscription Record Found Successful.','data':serializer.data}
                return Response(context, status=status.HTTP_201_CREATED)
            context = {'status': 0,'message': 'Invailid.',}
            return Response(context, status=status.HTTP_201_CREATED)

        except Exception as e:
            logger.error('SubscriptionAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message']}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)

    def get(self, request,id=None):
        try:   
            if id is not None:
                users=Subscription.objects.get(id=id)
                serializer = self.serializer_class(users,many=False)
                context = {'status': 1,'message': 'Subscription User Record Found Successfully.','data':serializer.data}
                return Response(context, status=status.HTTP_200_OK)
            users=Subscription.objects.all()
            serializer = self.serializer_class(users,many=True)
            context = {'status': 1,'message': 'Subscription User Record Found Successfully.','data':serializer.data}
            return Response(context, status=status.HTTP_200_OK)
        except Exception as e:
            logger.error('SubscriptionAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message']}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)
    


#Profile API  
class MagazineProfileAPIView(generics.GenericAPIView):
    serializer_class = GetMagazineProfileSerializer
    serializer_class = MagazineProfileSerializer
    serializer_class = UpdateProfileSerializer
    parser_classes = (FormParser, MultiPartParser)
    # permission_classes = (permissions.IsAuthenticated,)
    def get_serializer_class(self):
        if self.request.method == 'POST':
            return MagazineProfileSerializer
        elif self.request.method == 'PUT':
            return UpdateProfileSerializer

    def get(self, request,id=None):
        try:   
            user_id = self.request.GET.get('user_id', None)
            # user_id = self.request.query_params.get('user_id', None)
            # userobj = User.objects.filter(id=user_id)
            # if not userobj:
            #     context = {'status': 0,'message':'Please enter valid user id.'}
            #     return Response(context, status=status.HTTP_200_OK)

            if user_id:
                users=User.objects.get(id=user_id)
                serializer = GetMagazineProfileSerializer(users,many=False)
                context = {'status': 1,'message':'All user profile records found Successfully. ','data':[serializer.data]}
                return Response(context, status=status.HTTP_200_OK)
            users=User.objects.all()
            serializer = GetMagazineProfileSerializer(users,many=True)
            context = {'status': 1,'message':'All user profile records found Successfully. ','data':serializer.data}
            return Response(context, status=status.HTTP_200_OK)
        except Exception as e:
            logger.error('MagazineProfileAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message']}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)


    def post(self, request):
        try:
            data=request.data
            data['username']=data['email']
            data['email']=data['email']
            data['groups']=[0]
            data['roles']=5
            data['user_permissions']=[]
            otp_range = 4
            otp = ''.join(random.choices(string.digits, k = otp_range))
            data['otp']=otp
            now = datetime.datetime.now()
            now_plus_10 = now + timedelta(minutes = 3)
            data['exp_otp_datetime']=now_plus_10
            valid_ext = ('jpg','png')
            extention = (data['profile_pic'].name).split('.')[-1]
            if extention not in valid_ext:
                context = {'status': 0,'message':"Image extention should be '.jpg' or '.png'"}
                return Response(context, status=status.HTTP_201_CREATED)

            serializer = self.serializer_class(data=request.data)
            users=User.objects.filter(email__iexact=data['username']).last()
            if users:
                context = {'status': 0,'message':'Email already exists.'}
                return Response(context, status=status.HTTP_201_CREATED)

            phoneobj=User.objects.filter(phone_number=data['phone_number']).last()
            if phoneobj:
                context = {'status': 0,'message':'Phone number already exists.'}
                return Response(context, status=status.HTTP_201_CREATED)
            if serializer.is_valid():
                serializer.save(email_varification=True,phone_varification=True,otp_varification=True)
                users = User.objects.filter(username=serializer.data.get('username',None)).last()
                record_data = {'username':users.username,'current_otp':users.otp, 'name':users.first_name}
                RegisterMailToUserThread(record_data).start()
                context = {'status': 1,'message': register_message['message'],'data':serializer.data}
                return Response(context, status=status.HTTP_201_CREATED)
            context = {'status': 0,'message':'A user with that username already exists.','data': serializer.errors}
            return Response(context, status=status.HTTP_201_CREATED)
            
        except Exception as e:
            logger.error('MagazineProfileAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message']}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)


    def put(self, request):
        try:
            data=request.data
            profile=request.data.get('profile_pic',None)
            sortname=request.data.get('sortname',None)
            country_code=request.data.get('country_code',None)
            # print(request.data,"================+")
            if request.data.get('country_code') == '' or request.data.get('country_code') == None or request.data.get('country_code') =='null':
                # data = data.dict()
                data._mutable = True
                del data['country_code']

            ####################
            # country_code=request.data.get('country_code',None)
            # countryobj = Country.objects.filter(country_code=country_code).last()
            # print(countryobj)
            # print('countryobj',countryobj.id)
            
            # breakpoint()
            # data['country']=countryobj.id
            ######################
            
            if profile:
                valid_ext = ('jpg','png')
                extention = (data['profile_pic'].name).split('.')[-1]
                if extention not in valid_ext:
                    context = {'status': 0,'message':"Image extention should be '.jpg' or '.png'"}
                    return Response(context, status=status.HTTP_201_CREATED)

            if not profile:
                # print("In Profile")
                data = data.dict()
                del data['profile_pic']
            
            useronj = User.objects.get(id=data['user_id'])
            if not useronj:
                context = {'status': 0,'message': 'Please enter valid user id'}
                return Response(context, status=status.HTTP_201_CREATED)
            #######
            # print(useronj.country,'=========')
            # cc=countryobj.id if countryobj.id else useronj.country
            # pp=User.objects.filter(id=data['user_id']).update(country=cc)
            ###########3
            # country = Country.objects.filter(country_code = country_code,sortname=sortname).last()
            # data['country'] = country.id if country else None
            serializer = UpdateProfileSerializer(useronj,data)
            if serializer.is_valid():
                mkid=serializer.save()
                serializer_data=ShowUpdateProfileSerializer(mkid)
                # serializer.data['profile']=data['profile_pic']
                context = {'status': 1,'message': "Profile updated successfully.",'data':serializer_data.data}
                return Response(context, status=status.HTTP_201_CREATED)
            context = {'status': 0,'message':'User has not been update.','data': serializer.errors}
            return Response(context, status=status.HTTP_201_CREATED)
            
        except Exception as e:
            logger.error('MagazineProfileAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message']}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)
            

#  Contact us API  
class MagazineContactsAPIView(generics.GenericAPIView):
    serializer_class = ContactsSerializer

    def post(self, request):
        try:
            data=request.data
            data['user'] = data.get('user_id',None)
            # data['user'] = data['user_id'] if data['user_id'] else ""
           
            serializer = ContactsSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                users = ContactsUs.objects.filter(email=serializer.data.get('email',None)).last()
                # if data['email']:
                #     print('email varification data')

                record_data = {'username':data['email'],'message':users.message,'name':users.first_name}
                ContactMailToUserThread(record_data).start()
                # else:
                #     send_mobile_otp_to_user(data['phone_number'], otp)

                context = {'status': 1,'message': 'Contact User has been create successful.','data':serializer.data}
                return Response(context, status=status.HTTP_201_CREATED)
            context = {'status': 0,'message':'User has not been create data.','data': serializer.errors}
            return Response(context, status=status.HTTP_201_CREATED)
            
        except Exception as e:
            logger.error('MagazineContactsAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message']}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)

# Currency api
class MasterCurrencyAPIView(generics.GenericAPIView):
    serializer_class = MasterCurrencySerializer
    # permission_classes = (permissions.IsAuthenticated,)
    # permission_classes = (IsAuthenticated,)
    def post(self,request):
        try:
            serializer = self.serializer_class(data=request.data)
            if serializer.is_valid():
                serializer.save(currency_status=True)
                context = {'status': 1,'message': 'Master Currency Record Create Successful.','data':serializer.data}
                return Response(context, status=status.HTTP_201_CREATED)
            context = {'status': 0,'message': 'Master currency record is not create.','data':serializer.errors}
            return Response(context, status=status.HTTP_201_CREATED)

        except Exception as e:
            logger.error('MasterCurrencyAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message']}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)

    def get(self, request,id=None):
        try:   
            # if id is not None:
            #     users=Subscription.objects.get(id=id)
            #     serializer = self.serializer_class(users,many=False)
            #     context = {'status': 1,'message': 'Subscription User Record Found Successfully.','data':serializer.data}
            #     return Response(context, status=status.HTTP_200_OK)
            users=MasterCurrency.objects.all()
            serializer = self.serializer_class(users,many=True)
            context = {'status': 1,'message': 'Master Currency Record Found Successfully.','data':serializer.data}
            return Response(context, status=status.HTTP_200_OK)
        except Exception as e:
            logger.error('MasterCurrencyAPIView:error => ' + str(e))
            context = {'status': 0, 'message': Exp_MESSAGE['message']}
            return Response(context, status=status.HTTP_400_BAD_REQUEST)
    




