# -*- coding: utf-8 -*-
"""
sassets.helpers
===============

Helper functions.
"""

import os

from hashlib import md5


def calculate_file_hash(filepath):
    """Returns the hash value (string) of the contents in file `filepath`.
    """
    with open(filepath, 'rb') as _file:
        content = _file.read()
    return md5(content).hexdigest()


def filename_with_hash(filename, hash_value):
    """Returns a string where `hash_value` is mixed with `filename`.
    """
    if '.' in filename:  # filename has an extension?
        basename, extension = filename.rsplit('.', 1)
        return '%s.%s.%s' % (basename, hash_value, extension)
    return '%s%s' % (filename, hash_value)


def rename_asset(filepath, hash_value):
    """Rename asset file in `filepath` using `hash_value`.
    Returns the new filename (not the path, only the filename).
    """
    directory_path, old_filename = os.path.split(filepath)
    new_filename = filename_with_hash(old_filename, hash_value)
    new_filepath = os.path.join(directory_path, new_filename)
    os.rename(filepath, new_filepath)
    return new_filename
