# -*- 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.core.files.storage import FileSystemStorage
from django.conf import settings
from django.template.loader import get_template
from django.template import Context, TemplateDoesNotExist
from django.contrib.sites.models import Site


# 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(to, subject_template, body_template, context={}, attachements=[]):
    """
    Send a multialternative email based on html and optional txt template.
    """
    
    # Ensure arrays when needed
    if not isinstance(to, list):
        to = [to] 
    if not isinstance(attachements, list):
        attachements = [attachements]

    # Add domain in context
    context['domain'] = Site.objects.get_current()

    # If .html/.txt is specified in template name remove it
    body_template = body_template.split('.')[0]
    subject_template = subject_template.split('.')[0]

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

    # Get txt template for subject, fail if not exists
    subject_template = get_template('%s.txt' % (subject_template,))
    subject = subject_template.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' % (body_template,))
        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=subject, body=text_content, to=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'))
