from .models import *
from .serializer import *
from rest_framework.response import Response
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
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 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
from users.models import UserCredentialsForBlockchain
#from ScriptPad2.models import SPProject
from scriptAudit.models import ScriptAuditModel
#from ideamall2.models import Premise
from mnfapp.models import ReferUser


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 email_code.startswith("MR"):
            return '1' 
        elif email_code.startswith("IM"):
            return '2' 
        elif email_code.startswith("SD"):
            return '3'
        elif email_code.startswith("SB"):
            return '4' 
        elif email_code.startswith("CP"):
            return '5' 
        # elif email_code.startswith("PP"):
        #     return '6'
        elif email_code.startswith("PP"):
            return '7'
        elif email_code.startswith("ID"):
            return '8'
        # elif email_code.startswith("ID"):
        #     return '9' 
        elif email_code.startswith("GT"):
            return '10' 
        elif email_code.startswith("RM"):
            return '11'
        elif email_code.startswith("RN"):
            return '12' 
        elif email_code.startswith("TN"):
            return '13' 
        elif email_code.startswith("BL"):
            return '14'
        elif email_code.startswith("PM"):
            return '15'
        elif email_code.startswith("VW"):
            return '16' 
        else :
            pass
    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 '20'

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}/auto_email/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:
                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]
            file_path = f"{basepath}/auto_email/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]
            from_email = 'noreply@mynextfilm.ai'
            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]
            doodle_url = poster_url.iloc[0,4]
            dic_subject = str(row_data.iloc[0, 4]).replace('{}','').format_map(key_value)
            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('/')
            print("title", title)
            message = {'subject': dic_subject,
                    'title1': title[0],
                    'title2': title[1],
                    'invitation':dic_invitation,
                    'additional': dic_additional,
                    'poster': posterurl,
                    'pageurl':page_url,
                    'doodleurl':doodle_url,
                    'emailcode':email_code
                    }
            msg_html = render_to_string('email_template.html', message)
            excel_file = f"{basepath}/auto_email/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])   
            password = emails_creadentials.objects.get(email=from_email)
            print("before connection")
            #connection = get_connection(host=host,port=port,username=from_email,password=password.password,use_tls=True)
            from_email1 = "mynextfilm <noreply@mynextfilm>"

            # 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_email1,[to_email])
            print("after connection")
            sendMail.attach_alternative(msg_html,"text/html")
            if filePath is not None:
                sendMail.attach_file(f'{filePath}')
            # 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
            #     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 = "/static/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 = "/static/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 = "/static/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 = "/static/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 = "/static/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 = "/static/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 = "/static/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 = "/static/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 = "/static/Notification_image/subtitle.png")
            elif "script pad" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "script pad",image_url = "/static/Notification_image/scriptpad.png")
            elif "narration" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Narration",image_url = "/static/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 = "/static/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 = "/static/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 = "/static/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 = "/static/Notification_image/viewers_lounge.png")
            elif "Ask a question" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Ask a question",image_url = "/static/Notification_image/subtitle.png")
            elif "Payment" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Payment",image_url = "/static/Notification_image/payment.png")
            elif "blockchain" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "blockchain",image_url = "/static/Notification_image/blockchain.png")
            elif "Sheet14" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Sheet14",image_url = "/static/Notification_image/subtitle.png")
            elif "Institutional Membership" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "Institutional Membership",image_url = "/static/Notification_image/subtitle.png")
            elif "membershipReferences" in sheet_name:
                mnf_notification=Mnf_Notification(user=to_email,title=title[1],service_name = "membershipReferences",image_url = "/static/Notification_image/subtitle.png")
            else:
                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')
            mnf_notification.save()
            print("sendmail1")
            print("before send mail")
            sendMail.send()

            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()
    return




@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")