# -*- coding: utf-8 -*-
import os
import hashlib
import binascii
import base64
import html2text
from django.core.mail import EmailMultiAlternatives
from django.template import TemplateDoesNotExist


def str_or_none(obj):
    return str(obj) if obj else None


def ldap_hash(password):
    """Hash a password for use with LDAP.  If the password is already hashed,
    do nothing."""
    if password and not password.startswith('{SSHA}'):
        salt = binascii.hexlify(os.urandom(8))
        digest = hashlib.sha1(password.encode() + salt).digest()
        return '{SSHA}' + base64.b64encode(digest + salt).decode()
    else:
        return password


if __name__ == '__main__':
    print(ldap_hash('coin'))


def send_templated_email(subject, to, template_to_use, context, attachements, from_email=None):
    """
    Send a multialternative email based on html and optional txt template.
    """
    
    # Get default sender if not specified
    from_email = from_email if from_email else 'coin@illyse.org'
    
    # Ensure arrays when needed
    if not isinstance(to, list):
        to = [to] 
    if not isinstance(attachements, list):
        attachements = [attachements]

    # If .html is specified in template name remove it
    if template_to_use.endswith('.html'):
        template_to_use = template_to_use[:-5]

    # Get html template, fail if not exists
    template_html = get_template('%s.html' % (template_to_use,))
    html_content = template_html.render(Context(context))

    # Try to get a txt version, convert from html to markdown style
    # (using html2text) if fail
    try:
        template_txt = get_template('%s.txt' % (template_to_use,))
        text_content = template_txt.render_to_string(Context(context))
    except TemplateDoesNotExist:
        text_content = html2text.html2text(html_content)
    
    # make multipart email default : text, alternative : html
    msg = EmailMultiAlternatives(subject, text_content, from_email, to)
    msg.attach_alternative(html_content, "text/html")
    
    # Set attachements
    for attachement in attachements:
        msg.attach_file(attachement)

    #Send email
    msg.send()
