# from django.core.mail import EmailMultiAlternatives
# from django.utils.html import strip_tags
# from django.template.loader import render_to_string
# from django.conf import settings
# from MNF.settings import BasePath
# from django.core.mail import send_mail , get_connection
# from payment.models import privilegedUser1
# from django.contrib.auth.models import User
# from viewerLounge.models import VideoIntroduction, LifeMemberForm
# from lpp.models import MNFLPPDDatabase
# from harkat.models import HarkatClubDatabase
# from relationshipmanager.models import RMDatabase
# from mnfapp.models import centralDatabase
# import os
# from threading import Thread
# import time
# import pandas as pd
# from auto_email.models import emails_creadentials , auto_email_function_errors
# from MNF.settings import BasePath
from .models import *
from .serializer import *
#<<<<<<< Updated upstream
from rest_framework.response import Response

from rest_framework.response import Response 
#>>>>>>> Stashed changes
from rest_framework.decorators import (api_view, authentication_classes,
                                       permission_classes)
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.permissions import AllowAny, IsAuthenticated

# import time
# Create your views here.


# basepath = BasePath()
# def newfunc(list):
#     for i in list:
#         t = User.objects.filter(email=i)
#         if t.exists():
#             t = t[0]
#         username = t.first_name if t.first_name else t.email
#     return True

# def poster(user,email_code=None):
#     try:
#         data = User.objects.filter(email = user).values()
#         id = data[0]['id']
#         central_object = centralDatabase.objects.get(user_id=id)
#         if not central_object.isWhatsappJoined:
#             return '1'
#         elif not central_object.isNewsLetterSubscribed:
#             return '2'
#         elif not VideoIntroduction.objects.filter(user=id).exists():
#             return '3'
#         elif not MNFLPPDDatabase.objects.filter(user_id=id).exists():
#             return '4'
#         elif not HarkatClubDatabase.objects.filter(user_id=id).exists():
#             return '5'
#         elif not privilegedUser1.objects.filter(user=id).exists():
#             return '6'
#         elif not RMDatabase.objects.filter(user_id=id).exists():
#             return '7'
#         elif not central_object.isTelegramJoined:
#             return '8'
#         # elif not LifeMemberForm.objects.get(user=id).exists():
#         #     return '9'
#         # elif LifeMemberForm.objects.filter(user=id, showreel__isnull=True).exists():
#         #     return '10'
#         else:
#             return '9'
#     except Exception as e:
#         print(e)
#         auto_email_function_errors.objects.create(email = str(user),email_code=email_code,key_value={"test":"test"},error=str(e))
#         return '10'


# def mailer(all_email,email_code):
#     try:
#       for to_email in all_email:
#         sheet_code_excel = '/home/user/mnf/project/MNF/MNF/email/sheetCodeExcel.xlsx'
#         fileexcel = pd.read_excel(sheet_code_excel)
#         s1 = slice(0, 2)
#         string = email_code[s1]
#         value = fileexcel[fileexcel['sheet code'] == string]
#         if len(value) <= 0:
#             return ('Email code does not match with any sheet ')
#         sheet_name = value.iloc[0, 1]
#         file_path = "/home/user/mnf/project/MNF/MNF/email/EMAILSheet.xlsx"
#         file = pd.read_excel(file_path, sheet_name=sheet_name, header=1)
#         row_data = file[file['Email Code'] == str(email_code)]
#         if len(row_data) <= 0:
#             return 'Email code is not present in any sheet'
#         row_data = row_data.fillna('')
#         from_email = row_data.iloc[0, 3]
#         additional_option_code = row_data.iloc[0, 7]
#         option_file = pd.read_excel(
#             file_path, sheet_name='Common Options', header=1)
#         option_details = option_file[option_file['CODE'] == str(
#             additional_option_code)]
#         if len(option_details) <= 0:
#             return 'options code does not match with sheet options code'
#         poster_file = pd.read_excel(file_path, sheet_name='poster', header=1)
#         poster_code = poster(user=to_email)
#         postercode = 'P'+str(poster_code)
#         if poster_code == '12':
#             return 'user has not any priority to send poster'
#         poster_url = poster_file[poster_file['Poster code'] == str(postercode)]
#         posterurl = poster_url.iloc[0, 2]
#         title = row_data.iloc[0, 5].split('/')
#         message = {'subject': row_data.iloc[0, 4],
#                 'title1': title[0],
#                 'title2': title[1],
#                 'invitation': row_data.iloc[0, 4],
#                 'additional': option_details.iloc[0, 2],
#                 'poster': posterurl,
#                 }
#         msg_html = render_to_string('email_templete.html', message)
#         excel_file = "/home/user/mnf/project/MNF/MNF/email/EmailCredentials.xlsx"
#         details = pd.read_excel(excel_file)
#         email_data = details[details['email'] == str(from_email)]
#         host = email_data.iloc[0, 1]
#         port = int(email_data.iloc[0, 2])
<<<<<<< Updated upstream
#         password = emails_creadentials.objects.get(email=from_email)
=======
#         password = emails_creadentials.objects.get(email=from_email)  
>>>>>>> Stashed changes
#         connection = get_connection(host=host,port=port,username=from_email,password=password.password,use_tls=True)
#         send_mail(message['subject'],title[1],from_email=from_email,recipient_list=[to_email],html_message=msg_html,connection=connection)
#         notification=Mnf_Notification(user=to_email,title=title[1])
#         notifiaction.save()
#       return
#     except Exception as error:
#       pass

# def sendmail(to_email,email_code,key_value=None,filePath=None):
#     # start_time = time.process_time()
#     # t = Thread(target=mailer,args=(to_email,email_code,key_value,filePath))
#     t = Thread(target=mailer,args=(to_email,email_code))
#<<<<<<< Updated upstream


    
#>>>>>>> Stashed changes
#     t.start()
#     # t = mailer(to_email,email_code,key_value)
#     # print(t)
#     # time.sleep(1)
#     # print("email func has taken", time.process_time()-start_time, "time")
#<<<<<<< Updated upstream
#     return
 
#>>>>>>> Stashed changes

from django.core.mail import EmailMultiAlternatives
from django.utils.html import strip_tags
from django.template.loader import render_to_string
from django.conf import settings
from MNF.settings import BasePath
from django.core.mail import send_mail , get_connection
from payment.models import privilegedUser1
from django.contrib.auth.models import User
from viewerLounge.models import VideoIntroduction
from lpp.models import MNFLPPDDatabase
from harkat.models import HarkatClubDatabase
# from relationshipmanager.models import RMDatabase
from mnfapp.models import centralDatabase
import os
from threading import Thread
import pandas as pd
from auto_email.models import emails_creadentials , auto_email_function_errors
from MNF.settings import BasePath
# Create your views here.


basepath = BasePath()
def newfunc(list):
    for i in list:
        t = User.objects.filter(email=i)
        if t.exists():
            t = t[0]
        username = t.first_name if t.first_name else t.email
    return True

def poster(user,email_code=None):
    try:
        data = User.objects.filter(email = user).values()
        id = data[0]['id']
        if not centralDatabase.objects.get(user_id=id).isWhatsappJoined:
            return '1'
        elif not centralDatabase.objects.get(user_id=id).isNewsLetterSubscribed:
            return '2'
        elif not VideoIntroduction.objects.filter(user=id).exists():
            return '3'
        elif not MNFLPPDDatabase.objects.filter(user_id=id).exists():
            return '4'
        elif not HarkatClubDatabase.objects.filter(user_id=id).exists():
            return '5'
        elif not privilegedUser1.objects.filter(user=id).exists():
            return '6'
<<<<<<< Updated upstream
        elif not RMDatabase.objects.filter(user_id=id).exists():
            return '7'
=======
        # elif not RMDatabase.objects.filter(user_id=id).exists():
        #     return '7'
>>>>>>> Stashed changes
        elif not centralDatabase.objects.get(user_id=id).isTelegramJoined:
            return '8'
        # elif not LifeMemberForm.objects.get(user=id).exists():
        #     return '9'
        # elif LifeMemberForm.objects.filter(user=id, showreel__isnull=True).exists():
        #     return '10'
        else:
            return '9'
    except Exception as e:
        print(e)
        auto_email_function_errors.objects.create(email = str(user),email_code=email_code,key_value={"test":"test"},error=str(e))
        return '10'

def mailer(all_email,email_code,key_value,filePath):
    print('basepath',basepath)
    try:
        if not key_value:
            key_value={}
        for to_email in all_email:
            try:
                try:
                    name = centralDatabase.objects.filter(email = to_email)
                    if name.exists():
                        name = name[0]
                    userName = name.firstName if name.firstName else name.email
                except:
                    name = User.objects.filter(email = to_email)
                    if name.exists():
                        name = name[0]
                    userName = name.first_name if name.first_name else name.email
            except:
                userName = to_email
            key_value.update({"User":userName})
            sheet_code_excel = f'{basepath}/MNF/email/sheetCodeExcel.xlsx'
            fileexcel = pd.read_excel(sheet_code_excel)
            s1 = slice(0, 2)
            string = email_code[s1]
            print("string",string)
            value = fileexcel[fileexcel['sheet code'] == string]
            print("value",value)
            if len(value) <= 0:
                auto_email_function_errors.objects.create(email = to_email,email_code=email_code,key_value=key_value,error="Email code does not match with any sheet ")
                return print(('Email code does not match with any sheet'))
            sheet_name = value.iloc[0, 1]
            print("sheetname",sheet_name)
            file_path = f"{basepath}/MNF/email/EMAILSheet39.xlsx"
            file = pd.read_excel(file_path, sheet_name=sheet_name, header=1)
            row_data = file[file['Email Code'] == str(email_code)]
            if len(row_data) <= 0:
                auto_email_function_errors.objects.create(email = to_email,email_code=email_code,key_value=key_value,error="Email code is not present in any sheet")
                return print('Email code is not present in any sheet')
            row_data = row_data.fillna('')
            from_email = row_data.iloc[0, 3]
            print(from_email,"from_email")
            additional_option_code = row_data.iloc[0, 7]
            option_file = pd.read_excel(
                file_path, sheet_name='Common Options', header=1)
            option_details = option_file[option_file['CODE'] == str(
                additional_option_code)]
            if len(option_details) <= 0:
                auto_email_function_errors.objects.create(email = to_email,email_code=email_code,key_value=key_value,error='options code does not match with sheet options code')
                return print('options code does not match with sheet options code')
            poster_file = pd.read_excel(file_path, sheet_name='poster', header=1)
            poster_code = poster(user=to_email,email_code = email_code)
            postercode = 'P'+str(poster_code)
            if poster_code == '11':
                auto_email_function_errors.objects.create(email = to_email,email_code=email_code,key_value=key_value,error="user has not any priority to send poster")
                return print('user has not any priority to send poster')
            poster_url = poster_file[poster_file['Poster code'] == str(postercode)]
            posterurl = poster_url.iloc[0, 2]
            page_url = poster_url.iloc[0,3]
<<<<<<< Updated upstream

            dic_subject = str(row_data.iloc[0, 4]).replace('{}','').format_map(key_value)
=======
            
            dic_subject = str(row_data.iloc[0, 4]).replace('{}','').format_map(key_value)   
>>>>>>> Stashed changes
            dic_invitation = str(row_data.iloc[0, 6]).replace('{}','').format_map(key_value)
            dic_additional = str(option_details.iloc[0, 2]).replace('{}','').format_map(key_value)
            title = str(row_data.iloc[0, 5]).replace('{}','').format_map(key_value).split('/')
            message = {'subject': dic_subject,
                    'title1': title[0],
                    'title2': title[1],
                    'invitation':dic_invitation,
                    'additional': dic_additional,
                    'poster': posterurl,
                    'pageurl':page_url,
                    'emailcode':email_code
                    }
            print('doneeee')
<<<<<<< Updated upstream
            msg_html = render_to_string('email_template2.html', message)
            excel_file = f"{basepath}/MNF/email/EmailCredentials.xlsx"
=======
            msg_html = render_to_string('email_template.html', message)
            print('msg_html')
            excel_file = f"{basepath}/MNF/email/EmailCredentials.xlsx"
            print('exlefile', excel_file)
>>>>>>> Stashed changes
            details = pd.read_excel(excel_file)
            print('details')
            email_data = details[details['email'] == str(from_email)]
            print('email_sas')
            host = email_data.iloc[0, 1]
            print('hosj')
            port = int(email_data.iloc[0, 2])
            print('pass1')
            password = emails_creadentials.objects.get(email=from_email)  
            print('pass2')
            connection = get_connection(host=host,port=port,username=from_email,password=password.password,use_tls=True)
            print('conn1')
            # send_mail(message['subject'],title[1],from_email=from_email,recipient_list=[to_email],html_message=msg_html,connection=connection)
            sendMail = EmailMultiAlternatives(message['subject'],title[1],from_email,to=[to_email],connection=connection)
            print('con2')
            sendMail.attach_alternative(msg_html,"text/html")
            print('texthtml')
            if filePath is not None:
                sendMail.attach_file(f'{filePath}')
<<<<<<< Updated upstream

            # if sheet_name == "Rendz (traction)":
            #     notification=Mnf_Notification(user=to_email,title=title[1],service_name = sheet_name,image_url = "/media/Notification_image/build_team.png")
            # elif sheet_name == "membershipReferences":
            #     notification=Mnf_Notification(user=to_email,title=title[1],service_name = sheet_name,image_url = "/media/Notification_image/pitchdeck.png")
            # elif sheet_name == "Misc.":cd
=======
            print('notnone')
            # if sheet_name == "Rendz (traction)":
            #     notification=Mnf_Notification(user=to_email,title=title[1],service_name = sheet_name,image_url = "/media/Notification_image/build_team.png")
            # elif sheet_name == "membershipReferences":
            #     notification=Mnf_Notification(user=to_email,title=title[1],service_name = sheet_name,image_url = "/media/Notification_image/pitchdeck.png") 
            # elif sheet_name == "Misc.":cd 
>>>>>>> Stashed changes
            #     notification=Mnf_Notification(user=to_email,title=title[1],service_name = sheet_name,image_url = "/media/Notification_image/ideamall.png")
            if "Idea Mall" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Idea Mall",image_url = "/media/Notification_image/Idea_Mall.png")
            elif "Conversion - LPP" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Conversion - LPP",image_url = "/media/Notification_image/Conversion_LPP.png")
            elif "Script Builder" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Script Builder",image_url = "/media/Notification_image/Script_Builder.png")
            elif "Messiah" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Messiah",image_url = "/media/Notification_image/Messiah.png")
            elif "Project Centre" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Project Centre",image_url = "/media/Notification_image/Project_Centre.png")
            elif "Harkat" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Harkat",image_url = "/media/Notification_image/Harkat.png")
            elif "Pitchdeck Bundle" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Pitchdeck Bundle",image_url = "/media/Notification_image/Pitchdeck_Bundle.png")
            elif "Script page" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Script Page",image_url = "/media/Notification_image/Script_page.png")
            elif "subtitle" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Subtitle",image_url = "/media/Notification_image/subtitle.png")
            # elif "script pad":
            #     notification=Mnf_Notification(user=to_email,title=title[1],service_name = sheet_name,image_url = "/media/Notification_image/subtitle.png")
            elif "narration" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Narration",image_url = "/media/Notification_image/narration.png")
            elif "Institutional Membership" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Institutional Membership",image_url = "/media/Notification_image/Institutional_Membership.png")
            elif "LPP - Admininstration" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "LPP - Admininstration",image_url = "/media/Notification_image/LPP_Admininstration.png")
            elif "Conversion ppt" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Conversion PPT",image_url = "/media/Notification_image/Conversion_ppt.png")
            elif "viewers lounge" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Viewers Lounge",image_url = "/media/Notification_image/viewers_lounge.png")
            # elif "Ask a question":
            #     notification=Mnf_Notification(user=to_email,title=title[1],service_name = sheet_name,image_url = "/media/Notification_image/subtitle.png")
            # elif sheet_name == "Payment":
            #     notification=Mnf_Notification(user=to_email,title=title[1],service_name = sheet_name,image_url = "/media/Notification_image/payment.png")
            # elif sheet_name == "blockchain":
            #     notification=Mnf_Notification(user=to_email,title=title[1],service_name = sheet_name,image_url = "/media/Notification_image/blockchain.png")
            # elif sheet_name == "Sheet14":
            #     notification=Mnf_Notification(user=to_email,title=title[1],service_name = sheet_name,image_url = "/media/Notification_image/subtitle.png")
            # elif sheet_name == "Institutional Membership":
            #     notification=Mnf_Notification(user=to_email,title=title[1],service_name = sheet_name,image_url = "/media/Notification_image/subtitle.png")
            # elif sheet_name == "Institutional Membership":
            #     notification=Mnf_Notification(user=to_email,title=title[1],service_name = sheet_name,image_url = "/media/Notification_image/subtitle.png")
            else:
<<<<<<< Updated upstream
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = sheet_name)
            # from plyer import notification
            # notification.notify(title = sheet_name,message = title[1],timeout=100,app_icon = f'{basepath}/media/Notification_image/Conversion_ppt.png',app_name=sheet_name )
=======
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = sheet_name)   
            # from plyer import notification
            # notification.notify(title = sheet_name,message = title[1],timeout=100,app_icon = f'{basepath}/media/Notification_image/Conversion_ppt.png',app_name=sheet_name )
            print('mnf_not')
>>>>>>> Stashed changes
            mnf_notification.save()
            print("sendmail1")
            sendMail.send()
<<<<<<< Updated upstream

=======
            
>>>>>>> Stashed changes
            print('done compete notification')
        return
    except Exception as error:
        print(error)
        auto_email_function_errors.objects.create(email = to_email,email_code=email_code,key_value=key_value,error=str(error))
        pass
 

def sendmail(to_email,email_code,key_value=None,filePath=None):
    t = Thread(target=mailer,args=(to_email,email_code,key_value,filePath))
    t.start()
    # t = mailer(to_email,email_code,key_value)
    # print(t)
<<<<<<< Updated upstream
    return
=======
    return 
>>>>>>> Stashed changes




@api_view(["GET", "DELETE", "POST", "PUT", "PATCH"])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
def mnf_notification(request,pk=None):
    if request.method == "GET":
        if pk is not None:
            main = Mnf_Notification.objects.all().filter(user=pk)
            if main:

                serializer = Mnf_NotificationSerializer(main,many=True)
                return Response(serializer.data)
            else:
                return Response([])

        main = Mnf_Notification.objects.all()
        serializer = Mnf_NotificationSerializer(main, many=True)
        return Response(serializer.data)
    if request.method == "PATCH":
        main = Mnf_Notification.objects.get(id=pk)
        serializer = Mnf_NotificationSerializer(main, data=request.data ,partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response("partial data updated")
        return Response(serializer.errors)
    if request.method == "DELETE":
        if pk is not None:
            main = Mnf_Notification.objects.filter(id=pk)
        # else:
        #     main = MemberProfile.objects.filter(projectid=pk)
        main.delete()
        return Response("data deleted")