import hashlib
import json
import os
import pickle
import shutil
from datetime import date, datetime

from django.conf import settings
from django.utils import timezone

from django_test_tools.exceptions import DjangoTestToolsException

BLOCKSIZE = 65536


def create_dated(filename):
    """
    Based on the filename will create a full path filename including the date and time in '%Y%m%d_%H%M' format.
    The path to the filename will be set in the TEST_OUTPUT_PATH settings variable.

    If the TEST_OUTPUT_PATH folder doesn't exist the function will create it.

    :param filename: base filename. my_excel_data.xlsx for example
    :return: string, full path to file with date and time in the TEST_OUTPUT_PATH folder
    """
    if getattr(settings, 'TEST_OUTPUT_PATH', None) is None:
        msg = 'You need a the variable TEST_OUTPUT_PATH in settings. It should point to a folder' \
              'for temporary data to be written and reviewed.'
        raise ValueError(msg)
    if not os.path.exists(settings.TEST_OUTPUT_PATH):
        os.makedirs(settings.TEST_OUTPUT_PATH)
    return add_date(os.path.join(settings.TEST_OUTPUT_PATH, filename))


def hash_file(filename, algorithm='sha1', block_size=BLOCKSIZE):
    """
    Creates a unique hash for a file.

    :param filename: String with the full path to the file
    :param algorithm: String Algorithm to create the hash
    :param block_size: int for the size of the block while reading the file
    :return: string the hash for the file
    """
    try:
        hasher = getattr(hashlib, algorithm)()
    except AttributeError:
        raise ValueError('{} is not a valid hashing algorithm'.format(algorithm))

    with open(filename, 'rb') as afile:
        buf = afile.read(block_size)
        while len(buf) > 0:
            hasher.update(buf)
            buf = afile.read(block_size)
    return hasher.hexdigest()


def parametrized(dec):
    """
    Need to study this code.
    Got it from http://stackoverflow.com/questions/5929107/python-decorators-with-parameters