## -*- coding: utf-8 -*-

__author__ = 'SDE'

from django.core.mail import EmailMultiAlternatives
# from AuthApp.models import UserProfileModel
import smtplib
# from tEDataProj.settings import prod_server
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from os.path import basename
from email.mime.base import MIMEBase
from email import encoders
import ssl
import time
import random
# from tEDataProj import settings
from django.conf import settings


# tech@truenergy.by
# k7n2d3ZFZo4@CU5$4YDk

# administrator@truenergy.by
# 6&#WfW8$qR2w8uv69e5$


# def fix_mailing_links_in_mail(html):
#     from GeneralApp.views import get_cur_domain
#     serv_domain, client_domain = get_cur_domain()
#
#     while 'src="/media/' in html:
#         html = html.replace('src="/media/', f'src="{serv_domain}media/')
#
#     return html


def mailing_direct_by_maillist(subject, from_email, to, html_content, attachments=None):
    log = ''
    for email in to:
        res = admin_send_mail_by_SMTPlib(subject, from_email, email, html_content, attachments)
        # print(str(res))
        log = '{0}<br>{1}'.format(log, str(res))
        time.sleep(random.randint(1, 5))

    return log


def prepare_attach_file(filepath, filename=None):
    try:

        if not filename:
            filename = basename(filepath)

        if not settings.MEDIA_ROOT in filepath:
            filepath = f'{settings.MEDIA_ROOT}{filepath}'

        with open(filepath, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=filename
            )
        # After the file is closed
        part['Content-Disposition'] = 'attachment; filename="%s"' % filename
    except Exception as e:
        msg = f'prepare_attach_file Error = {str(e)}'
        techSendMail(msg, title='prepare_attach_file')
        return msg

    return part


def prepare_xls_attach_by_xls_virtual_file(virtual_file, filename):
    ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    # with open(filepath, 'rb') as fp:
    file = MIMEBase(maintype, subtype)  # Используем общий MIME-тип
    file.set_payload(virtual_file)  # Добавляем содержимое общего типа (полезную нагрузку)
    # fp.close()
    encoders.encode_base64(file)  # Содержимое должно кодироваться как Base64

    file.add_header('Content-Disposition', 'attachment', filename=filename)

    return file


def admin_send_mail_by_SMTPlib(subject, from_email, to, html_content, attachments=None):
    res = None

    try:
        # smtp_server = 'mail.cln.by'  # 'mail.truenergy.by'
        # smtp_port = 2525  # 587
        # smtp_password = 'clNdt6a8a'  # u'98q3$IjxH%RUIxySw8R2'
        # smtp_login = 'support@cln.by'  # 'support@truenergy.by'
        # from_email = smtp_login

        try:
            smtp_server = 'mail.truenergy.by'
            smtp_port = 587
            smtp_password = 'eg4$#95Xp0T*V%ig5BbR'
            smtp_login = 'support@truenergy.by'
            res = send_mail_by_SMTPlib(subject, from_email, to, html_content, smtp_server, smtp_port, smtp_login,
                                       smtp_password, attachments)
        except:
            smtp_server = 'mail.truenergy.by'
            smtp_port = 25
            smtp_password = 'PowH@aL0a4%$iz0Uo5V$'
            smtp_login = 'tech@truenergy.by'
            res = send_mail_by_SMTPlib(subject, smtp_login, to, html_content, smtp_server, smtp_port, smtp_login,
                                       smtp_password, attachments)

    except Exception as e:
        # from Baldenini_site.SMS_sender import send_SMS
        # send_SMS(u'375296177827', u'send_mail_by_SMTPlib error = {0}'.format(str(e)), urgent=True)
        msg = 'admin_send_mail_by_SMTPlib error = {0}'.format(str(e))
        print(msg)
        # techSendMail(msg)

    return str(res)


def send_mail_by_SMTPlib(subject, from_email, to_init, html_content, smtp_server, smtp_port, smtp_login, smtp_password,
                         attachments=None):
    to = to_init
    if not settings.prod_server:
        to = 'web@syncsystems.net'
    else:
        to = to_init
        try:
            from settings_local import DEBUG
        except:
            print('get settings_local fail')

    res = None
    mail_lib = None

    time.sleep(1)

    try:
        # context = ssl.create_default_context()

        mail_lib = smtplib.SMTP(smtp_server, smtp_port)

        res = mail_lib.ehlo()

        res = mail_lib.starttls()  # context=context)
        # print('mail_lib.starttls = {0}'.format(str(res)))

        res = mail_lib.ehlo()
        # print('mail_lib.ehlo = {0}'.format(str(res)))

        res = mail_lib.set_debuglevel = 2
        # print('mail_lib.set_debuglevel = {0}'.format(str(res)))

        res = mail_lib.esmtp_features['auth'] = 'LOGIN PLAIN'
        # print('mail_lib.esmtp_features = {0}'.format(str(res)))

        res = mail_lib.login(smtp_login, smtp_password)
        # print('mail_lib.login = {0}'.format(str(res)))

        res = None

        if type(to) in (list, tuple):
            if 'support@truenergy.by' in to:
                to.remove('support@truenergy.by')

            if len(to) > 1:
                to_str = u', '.join(to)
            else:
                to_str = to[0]
        else:
            if to == 'support@truenergy.by':
                return None
            to_str = to
            to = []
            to.append(to_str)

        if type(subject) != str:
            try:
                subject = subject.decode('utf-8')
            except:
                try:
                    subject = subject.encode('utf-8')
                except:
                    pass

        msg = MIMEMultipart()
        from email.headerregistry import Address
        msg['From'] = from_email
        msg['Reply-To'] = from_email
        # msg['In-Reply-To'] = "email2@example.com"
        msg['To'] = to_str
        msg['Subject'] = subject
        msg.attach(MIMEText(html_content, 'html', 'utf-8'))

        # print('attach message complete')

        if attachments:
            if type(attachments) in (list, tuple):
                try:
                    for item in attachments:
                        res = msg.attach(item)
                        # print('attach file complete = {0}'.format(str(res)))
                except:
                    res = msg.attach(attachments)
                    # print('except attach file complete = {0}'.format(str(res)))
            else:
                res = msg.attach(attachments)
                # print('else attach file complete = {0}'.format(str(res)))

        res = mail_lib.sendmail(from_email, to, msg.as_string())

        msg = mail_lib.quit()
        # print('mail_lib.quit = {0}'.format(str(msg)))

    except Exception as e:
        # from Baldenini_site.SMS_sender import send_SMS
        # send_SMS(u'375296177827', u'send_mail_by_SMTPlib error = {0}'.format(str(e)), urgent=True)
        msg = 'send_mail_by_SMTPlib error = {0}'.format(str(e))
        print(msg)
        try:
            mail_lib.quit()
            # print('mail_lib.quit = {0}'.format(str(msg)))
        except:
            pass

        try:
            print(str(mail_lib.__dict__))
        except:
            pass

        return msg
        # techSendMail(msg)

    msg = 'send_mail_by_SMTPlib subj={3} init_to={2} to={0} res={1}'.format(str(to), str(res), str(to_init),
                                                                            str(subject))
    print(msg)

    return msg


def sendMail(subject, text_content, from_email, to, html_content):
    print('sendMail to {0}'.format(str(to)))

    admin_send_mail_by_SMTPlib(subject, from_email, [to], html_content)

    # msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    # msg.attach_alternative(html_content, "text/html")
    # msg.send()
    print(u'Accept')
    return u'Accept'


# def techSendMail_for_top_management(html_content, title=None):
#     try:
#
#         # if not prod_server:
#         #     msg = '{0}. Not sended because is local'.format(html_content)
#         #     print(msg)
#         #     return msg
#         from AuthApp.models import User
#         from django.db.models import Q
#
#         # to = ['web@syncsystems.net']
#         to = User.objects.filter(
#             Q(is_superuser=True) | Q(groups__name__in=[
#                 'Отдел продаж: Начальник отдела продаж', 'Управляющий',
#                 'Бухгалтерия: Главный бухгалтер'
#             ]),
#             is_active=True,
#             is_staff=True
#         ).values_list('email', flat=True)
#         to = list(to)
#         to.append('office@truenergy.by')
#
#         print('techSendMail_for_top_management')
#         if title:
#             subject = title
#         else:
#             subject = u'truEnergy Data техническое оповещение'
#         from_email = 'support@truenergy.by'
#
#         res = admin_send_mail_by_SMTPlib(subject, from_email, to, html_content)
#
#         # msg = EmailMultiAlternatives(subject, text_content, from_email, to)
#         # msg.attach_alternative(html_content, "text/html")
#         # msg.send()
#         print(res)
#         return u'Accept'
#
#     except Exception as e:
#         msg = 'techSendMail_for_top_management error={0}'.format(str(e))
#         techSendMail(msg)
#         print(msg)
#
#     return 'Fail'


def techSendMail_for_specified_email_list(html_content, email_list, title=None):
    try:

        print('techSendMail_for_specified_email_list')
        if title:
            subject = title
        else:
            subject = u'truEnergy Data техническое оповещение'
        from_email = 'support@truenergy.by'

        res = admin_send_mail_by_SMTPlib(subject, from_email, email_list, html_content)

        print(res)
        return u'Accept'

    except Exception as e:
        msg = 'techSendMail_for_specified_email_list error={0}'.format(str(e))
        techSendMail(msg)
        print(msg)

    return 'Fail'


def techSendMail(html_content, title=None, add_emails=None):
    # if not prod_server:
    #     msg = '{0}. Not sended because is local'.format(html_content)
    #     print(msg)
    #     return msg

    print('techSendMail')

    try:
        # subject = u'truEnergy Data техническое оповещение'
        from_email = 'support@truenergy.by'
        to = ['web@syncsystems.net']
        if add_emails:
            to.extend(add_emails)
        text_content = 'Technical message from truEnergy.'

        if title:
            subject = title
        else:
            subject = u'truEnergy Data техническое оповещение'

        res = admin_send_mail_by_SMTPlib(subject, from_email, to, html_content)

        print(res)

    except Exception as e:
        msg = 'techSendMail error={0}'.format(str(e))
        # techSendMail(msg)
        print(msg)

    return u'Accept'
