#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Copyright (c) 2016 Stephen Bunn
# GNU GPLv3 <https://www.gnu.org/licenses/gpl-3.0.en.html>

"""
decorators
.. module:: scrab
    :platform: Linux, MacOSX, Win32
    :synopsis:
    :created: 2016-10-06T21:00:06-04:00
    :modified: 2016-10-06T21:00:06-04:00
.. moduleauthor:: Stephen Bunn (ritashugisha@gmail.com)

"""

import time

from . import const


def logged_duration(log, reason='execute'):
    """ Log the duration of a function.
    :param log: The logging.Logger level funciton to log the duration
    :type log: logging.Logger.debug/info/warning/error/critical
    :param reason: The reason this function is executing, default 'execute'
    :type reason: str
    """

    def decorator(fn):
        def decorated(*args, **kwargs):
            _t1 = time.time()
            retn = fn(*args, **kwargs)
            log((
                '`{fn.__name__}` took `{t_delta} seconds` to {reason} ...'
            ).format(
                fn=fn,
                t_delta=(time.time() - _t1),
                reason=const.format(reason, *args, **kwargs)
            ))
            return retn
        return decorated
    return decorator
