# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os
import hashlib
import binascii
import base64
import html2text
from datetime import date, timedelta
from django.core.mail import EmailMultiAlternatives
from django.template import TemplateDoesNotExist
from django.core.files.storage import FileSystemStorage
from django.conf import settings


# Stockage des fichiers privés (comme les factures par exemple)
private_files_storage = FileSystemStorage(location=settings.PRIVATE_FILES_ROOT)

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


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

def delete_selected(modeladmin, request, queryset):
    """Overrides QuerySet's delete() function to remove objects one by one 
    so, that they are deleted in the LDAP (Redmine issue #195)."""
    for obj in queryset:
        obj.delete()

delete_selected.short_description = "Supprimer tous les objets sélectionnés."

# Time-related functions
def in_one_year():
    return date.today() + timedelta(365)

def start_of_month():
    return date(date.today().year, date.today().month, 1)

def end_of_month():
    return date(date.today().year, date.today().month + 1, 1) - timedelta(days=1)

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