import os
from django.core.mail import send_mail, EmailMessage

from app.entities import models
from django.conf import settings
from django.core import mail as email_connection
from django.db import transaction
# from weasyprint import HTML
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
from email.mime.text import MIMEText


def to_pdf():
    F = open(os.path.join(settings.EMAIL_TEMPLATES_ROOT, 'RMS-NEWUSER.html'), 'r')
    result = BytesIO()
    pdf = pisa.pisaDocument(F, result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None


@transaction.atomic
def batch_email_users(args):
    connection = email_connection.get_connection()
    messages = []
    connection.open()


    for data in args[0].iterator():
        name = data['name']
        username = data['username']
        password = data['password']
        recipient = data['email']
        admin = args[1]
        F = open(os.path.join(settings.EMAIL_TEMPLATES_ROOT, 'RMS-NEWUSER.html'), 'r')

        FC = F.read()

        FC = FC.replace('{name}', name)
        FC = FC.replace('{username}', username)
        FC = FC.replace('{password}', password)
        FC = FC.replace('{url}', settings.FRONT_END_URL + '/cms/profile')
        send_mail(
            subject='Resource Management System: Welcome!',
            message='',
            from_email=settings.EMAIL_DEFAULT_SENDER,
            recipient_list=(recipient,),
            html_message=FC,
            fail_silently=False
        )
        models.UserHistory.objects.filter(username=username).update(sent=True)
    connection.close()
    return True


def batch_email_admin(args):
    filename = args[0]
    recipient = args[1]
    body = """
    Dear Admin,

    Please see the attached file as your reference for the recent bulk users you have uploaded as an Administrator in RMS. 
    This email and any files transmitted with it are confidential and may contain privileged and confidential information, 
    including personal information protected by privacy laws.
    It is intended only for the use of the individual or entity to whom they are addressed.
    """
    msg = MIMEText(body)

    email = EmailMessage(
        'Resource Management System: Bulk Users!',
        body,
        settings.EMAIL_DEFAULT_SENDER,
        [recipient]
    )
    email.attach_file(filename)
    email.send()
    os.remove(filename)


def account_created(args):
    name = args[0]
    username = args[1]
    password = args[2]
    recipient = args[3]
    admin = args[4]

    F = open(os.path.join(settings.EMAIL_TEMPLATES_ROOT, 'RMS-NEWUSER.html'), 'r')

    FC = F.read()

    FC = FC.replace('{name}', name)
    FC = FC.replace('{username}', username)
    FC = FC.replace('{password}', password)
    FC = FC.replace('{url}', settings.FRONT_END_URL + '/cms/profile') #changed
    try:
        send_mail(
            subject='Resource Management System: Welcome!',
            message='',
            from_email=settings.EMAIL_DEFAULT_SENDER,
            recipient_list=(recipient,),
            html_message=FC,
            fail_silently=False
        )
        models.EmailLogs.objects.create(
            template='RMS-NEWUSER.html',
            recipients=recipient,
            content=FC,
            is_sent=True,
            createdby=admin,
            modifiedby=admin
        )
    except Exception as e:
        models.EmailLogs.objects.create(
            template='RMS-NEWUSER.html',
            recipients=recipient,
            content=FC,
            is_sent=False,
            createdby=admin,
            modifiedby=admin
        )
    return True


def cronjob(args):

    try:
        send_mail(
            subject='Resource Management System: Welcome!',
            message='',
            from_email=settings.EMAIL_DEFAULT_SENDER,
            recipient_list=('gladys@tirsolutions.com',),
            html_message="FC",
            fail_silently=False
        )
        models.EmailLogs.objects.create(
            template='RMS-NEWUSER.html',
            recipients="test",
            content="FC",
            is_sent=True,
            createdby=admin,
            modifiedby=admin
        )
    except Exception as e:
        models.EmailLogs.objects.create(
            template='RMS-NEWUSER.html',
            recipients="test",
            content="FC",
            is_sent=False,
            createdby="superuser",
            modifiedby="superuser"
        )
    return True

# direct mailer from django
def forgot_password(args):
    reset_code = args[0]
    url = args[1]
    recipient = args[2]
    admin = args[3]
    name = args[4]

    F = open(os.path.join(settings.EMAIL_TEMPLATES_ROOT, 'RMS-PASSWORD.html'), 'r')

    FC = F.read()

    FC = FC.replace('{name}', name)
    FC = FC.replace('{code}', reset_code)
    FC = FC.replace('{url}', url)

    send_mail(
        subject='Resource Management System: Reset Password',
        message='',
        from_email=settings.EMAIL_DEFAULT_SENDER,
        recipient_list=[recipient, admin,],
        html_message=FC
    )

    try:
        send_mail(
            subject='Resource Management System: Reset Password',
            message='',
            from_email=settings.EMAIL_DEFAULT_SENDER,
            recipient_list=recipient,
            html_message=FC,
            fail_silently=False
        )
        models.EmailLogs.objects.create(
            template='RMS-PASSWORD.html',
            recipients=recipient,
            content=FC,
            is_sent=True,
            createdby=admin,
            modifiedby=admin
        )
    except Exception as e:
        models.EmailLogs.objects.create(
            template='RMS-PASSWORD.html',
            recipients=recipient,
            content=FC,
            is_sent=False,
            createdby=admin,
            modifiedby=admin
        )


def admin_changepassword(args):
    name = args[0]
    username = args[1]
    password = args[2]
    recipient = args[3]
    admin = args[4]

    F = open(os.path.join(settings.EMAIL_TEMPLATES_ROOT, 'RMS-ADMINRESET.html'), 'r')

    FC = F.read()

    FC = FC.replace('{name}', name)
    FC = FC.replace('{username}', username)
    FC = FC.replace('{password}', password)
    FC = FC.replace('{url}', settings.FRONT_END_URL)

    send_mail(
        subject='Resource Management System: Password Changed',
        message='',
        from_email=settings.EMAIL_DEFAULT_SENDER,
        recipient_list=[recipient, admin,],
        html_message=FC
    )


# RMS-CRAPPROVED ; RMS-CRACKNOWLEDGE ; RMS-CRCOMPLETED ; RMS-CRACCEPTED ;
# RMS-CRREJECTED ; RMS-CRREJECTED-VENDOR ; RMS-CRREVISED ; RMS-CRCANCELLED-USERTRIGGER ;
# RMS-CRREJECTED-APPROVER

def routing_table_actions(args):

    email_template = ''

    name = args[0]
    action_by = args[1]
    routing_level = str(args[2])
    status = args[3]
    cr_number = args[4]
    cr_name = args[5]
    company_requestedto = args[6]
    department_requestedto = args[7]
    priority_level = args[8]
    url = args[9]
    remarks = str(args[10])
    
    recipient = args[11]
    action_type = args[12]
    delegation_type = args[13]
    delegation_recipient = args[14]
    admin = args[15]
    
    if args[12].lower() == 'approved':
        email_template = 'RMS-CRAPPROVED.html'
        subject = 'Resource Management System - Change Request Approved'
    elif args[12].lower() == 'acknowledged':
        email_template = 'RMS-CRACKNOWLEDGE.html'
        subject = 'Resource Management System - Change Request Acknowledged'
    elif args[12].lower() == 'completed':
        email_template = 'RMS-CRCOMPLETED.html'
        subject = 'Resource Management System - Change Request Completed'
    elif args[12].lower() == 'accepted':
        email_template = 'RMS-CRACCEPTED.html'
        subject = 'Resource Management System - Change Request Accepted'
    elif args[12].lower() == 'rejected':
        if args[14].lower() == 'requestor':
            subject = 'Resource Management System - Change Request Rejected'
            email_template = 'RMS-CRREJECTED.html'
        elif args[14].lower() == 'vendor':
            subject = 'Resource Management System - Action Required for Change Request'
            email_template = 'RMS-CRREVISED.html'
        elif args[14].lower() == 'approver':
            subject = 'Resource Management System - Action Required for Change Request'
            email_template = 'RMS-CRREJECTED-APPROVER.html'
    elif args[12].lower() == 'cancelled':
        subject = 'Resource Management System - Change Request Cancelled'
        email_template = 'RMS-CRCANCELLED-USERTRIGGER.html'
    
    F = open(os.path.join(settings.EMAIL_TEMPLATES_ROOT, email_template), 'r')
    
    FC = F.read()
    
    FC = FC.replace('{name}', name)
    FC = FC.replace('{action_by}', action_by)
    FC = FC.replace('{routing_level}', routing_level)
    FC = FC.replace('{status}', status)
    FC = FC.replace('{cr_number}', cr_number)
    FC = FC.replace('{cr_name}', cr_name)
    FC = FC.replace('{company_requestedto}', company_requestedto)
    FC = FC.replace('{department_requestedto}', department_requestedto)
    FC = FC.replace('{priority_level}', priority_level)
    FC = FC.replace('{url}', url)
    
    if args[12].lower() == 'rejected':
        FC = FC.replace('{remarks}', remarks)
        
    try:
        send_mail(
            subject=subject,
            message='',
            from_email=settings.EMAIL_DEFAULT_SENDER,
            recipient_list=(recipient,),
            html_message=FC,
            fail_silently=False
        )
        models.EmailLogs.objects.create(
            template=email_template,
            recipients=recipient,
            content=FC,
            is_sent=True,
            createdby=admin,
            modifiedby=admin
        )
    except Exception as e:
        models.EmailLogs.objects.create(
            template=email_template,
            recipients=recipient,
            content=FC,
            is_sent=False,
            createdby=admin,
            modifiedby=admin
        )
    return True


# RMS-ACTIONREQUIRED ; RMS-ACTIONREQUIRED-VENDOR
def routing_table_actions_required(args):
    name = args[0]
    cr_number = args[1]
    cr_name = args[2]
    company_requestedto = args[3]
    department_requestedto = args[4]
    priority_level = args[5]
    status = args[6]
    url = args[7]
    
    recipient = args[8]
    delegation_type = args[9]
    admin = args[10]
    
    if delegation_type.lower() == 'vendor/implementor':
        email_template = 'RMS-ACTIONREQUIRED-VENDOR.html'
        subject = 'Resource Management System - Action Required for Change Request'
    
    else:
        email_template = 'RMS-ACTIONREQUIRED.html'
        subject = 'Resource Management System - Action Required for Change Request'
            
    F = open(os.path.join(settings.EMAIL_TEMPLATES_ROOT, email_template), 'r')

    FC = F.read()
    
    FC = FC.replace('{name}', name)
    FC = FC.replace('{cr_number}', cr_number)
    FC = FC.replace('{cr_name}', cr_name)
    FC = FC.replace('{company_requestedto}', company_requestedto)
    FC = FC.replace('{department_requestedto}', department_requestedto)
    FC = FC.replace('{priority_level}', priority_level)
    FC = FC.replace('{status}', status)
    FC = FC.replace('{url}', url)
    
    try:
        send_mail(
            subject=subject,
            message='',
            from_email=settings.EMAIL_DEFAULT_SENDER,
            recipient_list=(recipient,),
            html_message=FC,
            fail_silently=False
        )
        models.EmailLogs.objects.create(
            template=email_template,
            recipients=recipient,
            content=FC,
            is_sent=True,
            createdby=admin,
            modifiedby=admin
        )
    except Exception as e:
        models.EmailLogs.objects.create(
            template=email_template,
            recipients=recipient,
            content=FC,
            is_sent=False,
            createdby=admin,
            modifiedby=admin
        )
    return True


# RMS-REMINDER-APPROVER
def routing_table_reminder_approver(args):
    name = args[0]
    auto_cancel_date = args[1]
    date_submitted_last_approver = args[2]
    cr_number = args[3]
    cr_name = args[4]
    company_requestedto = args[5]
    department_requestedto = args[6]
    priority_level = args[7]
    status = args[8]
    url = args[9]
    
    recipient = args[10]
    admin = args[11]
    
    F = open(os.path.join(settings.EMAIL_TEMPLATES_ROOT, 'RMS-REMINDER-APPROVER.html'), 'r')

    FC = F.read()

    FC = FC.replace('{name}', name)
    FC = FC.replace('{auto_cancel_date}', auto_cancel_date)
    FC = FC.replace('{date_submitted_last_approver}', date_submitted_last_approver)
    FC = FC.replace('{cr_number}', cr_number)
    FC = FC.replace('{cr_name}', cr_name)
    FC = FC.replace('{company_requestedto}', company_requestedto)
    FC = FC.replace('{department_requestedto}', department_requestedto)
    FC = FC.replace('{priority_level}', priority_level)
    FC = FC.replace('{status}', status)
    FC = FC.replace('{url}', url)
    
    try:
        send_mail(
            subject='Resource Management System - Awaiting Approval for Change Request',
            message='',
            from_email=settings.EMAIL_DEFAULT_SENDER,
            recipient_list=(recipient,),
            html_message=FC,
            fail_silently=False
        )
        models.EmailLogs.objects.create(
            template='RMS-REMINDER-APPROVER.html',
            recipients=recipient,
            content=FC,
            is_sent=True,
            createdby=admin,
            modifiedby=admin
        )
    except Exception as e:
        models.EmailLogs.objects.create(
            template='RMS-REMINDER-APPROVER.html',
            recipients=recipient,
            content=FC,
            is_sent=False,
            createdby=admin,
            modifiedby=admin
        )
    return True


# RMS-REMINDER-REQUESTOR
def routing_table_reminder_requestor(args):
    name = args[0]
    auto_cancel_date = args[1]
    date_submitted_last_approver = args[2]
    approver_pending_action = args[3]
    cr_number = args[4]
    cr_name = args[5]
    company_requestedto = args[6]
    department_requestedto = args[7]
    priority_level = args[8]
    status = args[9]
    url = args[10]
    
    recipient = args[11]
    admin = args[12]
            
    F = open(os.path.join(settings.EMAIL_TEMPLATES_ROOT, 'RMS-REMINDER-REQUESTOR.html'), 'r')

    FC = F.read()

    FC = FC.replace('{name}', name)
    FC = FC.replace('{auto_cancel_date}', auto_cancel_date)
    FC = FC.replace('{date_submitted_last_approver}', date_submitted_last_approver)
    FC = FC.replace('{approver_pending_action}', approver_pending_action)
    FC = FC.replace('{cr_number}', cr_number)
    FC = FC.replace('{cr_name}', cr_name)
    FC = FC.replace('{company_requestedto}', company_requestedto)
    FC = FC.replace('{department_requestedto}', department_requestedto)
    FC = FC.replace('{priority_level}', priority_level)
    FC = FC.replace('{status}', status)
    FC = FC.replace('{url}', url)
    
    try:
        send_mail(
            subject='Resource Management System - Awaiting Approval for Change Request',
            message='',
            from_email=settings.EMAIL_DEFAULT_SENDER,
            recipient_list=(recipient,),
            html_message=FC,
            fail_silently=False
        )
        models.EmailLogs.objects.create(
            template='RMS-REMINDER-REQUESTOR.html',
            recipients=recipient,
            content=FC,
            is_sent=True,
            createdby=admin,
            modifiedby=admin
        )
    except Exception as e:
        models.EmailLogs.objects.create(
            template='RMS-REMINDER-REQUESTOR.html',
            recipients=recipient,
            content=FC,
            is_sent=False,
            createdby=admin,
            modifiedby=admin
        )
    return True


# RMS-CRCANCELLED
def routing_table_cancelled(args):
    name = args[0]
    auto_cancel_date = args[1]
    date_submitted_last_approver = args[2]
    approver_pending_action = args[3]
    cr_number = args[4]
    cr_name = args[5]
    company_requestedto = args[6]
    department_requestedto = args[7]
    priority_level = args[8]
    status = args[9]
    url = args[10]
    
    recipient = args[11]
    admin = args[12]
            
    F = open(os.path.join(settings.EMAIL_TEMPLATES_ROOT, 'RMS-CRCANCELLED.html'), 'r')

    FC = F.read()

    FC = FC.replace('{name}', name)
    FC = FC.replace('{auto_cancel_date}', auto_cancel_date)
    FC = FC.replace('{date_submitted_last_approver}', date_submitted_last_approver)
    FC = FC.replace('{approver_pending_action}', approver_pending_action)
    FC = FC.replace('{cr_number}', cr_number)
    FC = FC.replace('{cr_name}', cr_name)
    FC = FC.replace('{company_requestedto}', company_requestedto)
    FC = FC.replace('{department_requestedto}', department_requestedto)
    FC = FC.replace('{priority_level}', priority_level)
    FC = FC.replace('{status}', status)
    FC = FC.replace('{url}', url)
    
    try:
        send_mail(
            subject='Resource Management System - Change Request Cancelled',
            message='',
            from_email=settings.EMAIL_DEFAULT_SENDER,
            recipient_list=(recipient,),
            html_message=FC,
            fail_silently=False
        )
        models.EmailLogs.objects.create(
            template='RMS-CRCANCELLED.html',
            recipients=recipient,
            content=FC,
            is_sent=True,
            createdby=admin,
            modifiedby=admin
        )
    except Exception as e:
        models.EmailLogs.objects.create(
            template='RMS-CRCANCELLED.html',
            recipients=recipient,
            content=FC,
            is_sent=False,
            createdby=admin,
            modifiedby=admin
        )
    return True


# RMS-CROVERDUE
def routing_table_overdue(args):
    name = args[0]
    target_date = args[1]
    cr_number = args[2]
    cr_name = args[3]
    company_requestedto = args[4]
    department_requestedto = args[5]
    priority_level = args[6]
    status = args[7]
    url = args[8]
    
    recipient = args[9]
    admin = args[10]
            
    F = open(os.path.join(settings.EMAIL_TEMPLATES_ROOT, 'RMS-CROVERDUE.html'), 'r')

    FC = F.read()

    FC = FC.replace('{name}', name)
    FC = FC.replace('{target_date}', target_date)
    FC = FC.replace('{cr_number}', cr_number)
    FC = FC.replace('{cr_name}', cr_name)
    FC = FC.replace('{company_requestedto}', company_requestedto)
    FC = FC.replace('{department_requestedto}', department_requestedto)
    FC = FC.replace('{priority_level}', priority_level)
    FC = FC.replace('{status}', status)
    FC = FC.replace('{url}', url)
    
    try:
        send_mail(
            subject='Resource Management System - Change Request Overdue',
            message='',
            from_email=settings.EMAIL_DEFAULT_SENDER,
            recipient_list=(recipient,),
            html_message=FC,
            fail_silently=False
        )
        models.EmailLogs.objects.create(
            template='RMS-CROVERDUE.html',
            recipients=recipient,
            content=FC,
            is_sent=True,
            createdby=admin,
            modifiedby=admin
        )
    except Exception as e:
        models.EmailLogs.objects.create(
            template='RMS-CROVERDUE.html',
            recipients=recipient,
            content=FC,
            is_sent=False,
            createdby=admin,
            modifiedby=admin
        )
    return True