# from: https://github.com/stefanholek/lazy
#
# Copyright (c) 2011-2017 Stefan H. Holek
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.


"""Decorator to create lazy attributes."""

import functools


class lazy:
    """
    Lazy descriptor.

    Used as a decorator to create lazy attributes. Lazy attributes
    are evaluated on first use.
    """

    def __init__(self, func):
        self.__func = func
        functools.wraps(self.__func)(self)

    def __get__(self, inst, inst_cls):
        if inst is None:
            return self

        if not hasattr(inst, "__dict__"):
            raise AttributeError(
                f"'{inst_cls.__name__}' object has no attribute '__dict__'"
            )

        name = self.__name__
        if name.startswith("__") and not name.endswith("__"):
            name = f"_{inst_cls.__name__}{name}"

        value = self.__func(inst)
        inst.__dict__[name] = value
        return value

    @classmethod
    def invalidate(cls, inst, name):
        """
        Invalidate a lazy attribute.

        This obviously violates the lazy contract. A subclass of lazy
        may however have a contract where invalidation is appropriate.
        """
        # These commands from the original are not currently used by larch and
        # are omitted for speed.  They are left here in case they are needed
        # for future compatibility.
        #
        # inst_cls = inst.__class__
        #
        # if not hasattr(inst, '__dict__'):
        #     raise AttributeError("'%s' object has no attribute '__dict__'" % (inst_cls.__name__,))
        #
        # if name.startswith('__') and not name.endswith('__'):
        #     name = '_%s%s' % (inst_cls.__name__, name)
        #
        # if not isinstance(getattr(inst_cls, name), cls):
        #     raise AttributeError("'%s.%s' is not a %s attribute"
        #                           % (inst_cls.__name__, name, cls.__name__))

        if name in inst.__dict__:
            del inst.__dict__[name]
