# coding: utf-8
"""Extension properties for Model, Shape, Boundary.

These objects hold all attributes assigned by extensions like fairyfly-therm.
Note that these Property objects are not intended to exist on their own and
should have a host object.
"""


class _Properties(object):
    """Base class for all Properties classes.

    Args:
        host: A fairyfly-core geometry object that hosts these properties
            (ie. Model, Shape, Boundary).
    """
    _exclude = set(
        ('host', 'move', 'rotate', 'rotate_xy', 'reflect', 'scale', 'is_equivalent',
         'reset_to_default', 'to_dict', 'apply_properties_from_dict', 'ToString'))

    def __init__(self, host):
        """Initialize properties."""
        self._host = host

    @property
    def host(self):
        """Get the object hosting these properties."""
        return self._host

    @property
    def _extension_attributes(self):
        return (atr for atr in dir(self) if not atr.startswith('_')
                and atr not in self._exclude)

    def move(self, moving_vec):
        """Apply a move transform to extension attributes.

        This is useful in cases where extension attributes possess geometric data
        that should be moved alongside the host object.

        Args:
            moving_vec: A ladybug_geometry Vector3D with the direction and distance
                to move the face.
        """
        for atr in self._extension_attributes:
            var = getattr(self, atr)
            if not hasattr(var, 'move'):
                continue
            try:
                var.move(moving_vec)
            except Exception as e:
                import traceback
                traceback.print_exc()
                raise Exception('Failed to move {}: {}'.format(var, e))

    def rotate(self, axis, angle, origin):
        """Apply a rotation transform to extension attributes.

        This is useful in cases where extension attributes possess geometric data
        that should be rotated alongside the host object.

        Args:
            axis: A ladybug_geometry Vector3D axis representing the axis of rotation.
            angle: An angle for rotation in degrees.
            origin: A ladybug_geometry Point3D for the origin around which the
                object will be rotated.
        """
        for atr in self._extension_attributes:
            var = getattr(self, atr)
            if not hasattr(var, 'rotate'):
                continue
            try:
                var.rotate(axis, angle, origin)
            except Exception as e:
                import traceback
                traceback.print_exc()
                raise Exception('Failed to rotate {}: {}'.format(var, e))

    def rotate_xy(self, angle, origin):
        """Apply a rotation in the XY plane to extension attributes.

        This is useful in cases where extension attributes possess geometric data
        that should be rotated alongside the host object.

        Args:
            angle: An angle in degrees.
            origin: A ladybug_geometry Point3D for the origin around which the
                object will be rotated.
        """
        for atr in self._extension_attributes:
            var = getattr(self, atr)
            if not hasattr(var, 'rotate_xy'):
                continue
            try:
                var.rotate_xy(angle, origin)
            except Exception as e:
                import traceback
                traceback.print_exc()
                raise Exception('Failed to rotate {}: {}'.format(var, e))

    def reflect(self, plane):
        """Apply a reflection transform to extension attributes.

        This is useful in cases where extension attributes possess geometric data
        that should be reflected alongside the host object.

        Args:
            plane: A ladybug_geometry Plane across which the object will
                be reflected.
        """
        for atr in self._extension_attributes:
            var = getattr(self, atr)
            if not hasattr(var, 'reflect'):
                continue
            try:
                var.reflect(plane)
            except Exception as e:
                import traceback
                traceback.print_exc()
                raise Exception('Failed to reflect {}: {}'.format(var, e))

    def scale(self, factor, origin=None):
        """Apply a scale transform to extension attributes.

        This is useful in cases where extension attributes possess geometric data
        that should be scaled alongside the host object.

        Args:
            factor: A number representing how much the object should be scaled.
            origin: A ladybug_geometry Point3D representing the origin from which
                to scale. If None, it will be scaled from the World origin (0, 0, 0).
        """
        for atr in self._extension_attributes:
            var = getattr(self, atr)
            if not hasattr(var, 'scale'):
                continue
            try:
                var.scale(factor, origin)
            except Exception as e:
                import traceback
                traceback.print_exc()
                raise Exception('Failed to scale {}: {}'.format(var, e))

    def is_equivalent(self, other_properties):
        """Get a dictionary noting the equivalency of these properties to other ones.

        The keys of this dictionary will note the name of each extension (eg.
        therm) and the values will be a boolean for whether the
        extension properties are equivalent or not.

        Args:
            other_properties: Properties of another object for which equivalency
                will be tested.
        """
        eq_dict = {}
        for atr in self._extension_attributes:
            var = getattr(self, atr)
            if not hasattr(var, 'is_equivalent'):
                continue
            other_var = getattr(other_properties, atr)
            try:
                eq_dict[atr] = var.is_equivalent(other_var)
            except Exception as e:
                import traceback
                traceback.print_exc()
                raise Exception('Failed test is_equivalent for {}: {}'.format(var, e))
        return eq_dict

    def _duplicate_extension_attr(self, original_properties):
        """Duplicate the attributes added by extensions.

        This method should be called within the duplicate or __copy__ methods of
        each fairyfly-core geometry object after the core object has been duplicated.
        This method only needs to be called on the new (duplicated) core object and
        the extension properties of the original core object should be passed to
        this method as the original_properties.

        Args:
            original_properties: The properties object of the original core
                object from which the duplicate was derived.
        """
        for atr in self._extension_attributes:
            var = getattr(original_properties, atr)
            if not hasattr(var, 'duplicate'):
                continue
            try:
                setattr(self, '_' + atr, var.duplicate(self.host))
            except Exception as e:
                import traceback
                traceback.print_exc()
                raise Exception('Failed to duplicate {}: {}'.format(var, e))

    def _reset_extension_attr_to_default(self):
        """Reset all extension attributes for the object to be default.

        This is useful in cases where properties that are hard-assigned to a specific
        object might be illegal in combination with other properties and so they
        should be reset upon the setting of the other properties.
        """
        for atr in self._extension_attributes:
            var = getattr(self, atr)
            if not hasattr(var, 'reset_to_default'):
                continue
            try:
                var.reset_to_default()
            except Exception as e:
                import traceback
                traceback.print_exc()
                raise Exception('Failed to reset_to_default for {}: {}'.format(var, e))

    def _add_extension_attr_to_dict(self, base, abridged, include):
        """Add attributes for extensions to the base dictionary.

        This method should be called within the to_dict method of each fairyfly-core
        geometry object.

        Args:
            base: The dictionary of the core object without any extension attributes.
                This method will add extension attributes to this dictionary. For
                example, energy properties will appear under base['properties']['energy'].
            abridged: Boolean to note whether the attributes of the extensions should
                be abridged (True) or full (False). For example, if a Room's energy
                properties are abridged, the program_type attribute under the energy
                properties dictionary will just be the identifier of the program_type. If
                it is full (not abridged), the program_type will be a complete
                dictionary following the ProgramType schema. Abridged dictionaries
                should be used within the Model.to_dict but full dictionaries should
                be used within the to_dict methods of individual objects.
            include: List of properties to filter keys that must be included in
                output dictionary. For example ['energy'] will include 'energy' key if
                available in properties to_dict. By default all the keys will be
                included. To exclude all the keys from extensions use an empty list.
        """
        attr = include if include is not None else self._extension_attributes
        for atr in attr:
            var = getattr(self, atr)
            if not hasattr(var, 'to_dict'):
                continue
            try:
                base.update(var.to_dict(abridged))
            except Exception as e:
                import traceback
                traceback.print_exc()
                raise Exception('Failed to convert {} to a dict: {}'.format(var, e))
        return base

    def _load_extension_attr_from_dict(self, property_dict):
        """Get attributes for extensions from a dictionary of the properties.

        This method should be called within the from_dict method of each fairyfly-core
        geometry object. Specifically, this method should be called on the core
        object after it has been created from a dictionary but lacks any of the
        extension attributes in the dictionary.

        Args:
            property_dict: A dictionary of properties for the object (ie.
                ShapeProperties, BoundaryProperties). These will be used to load
                attributes from the dictionary and assign them to the object on
                which this method is called.
        """
        for atr in self._extension_attributes:
            var = getattr(self, atr)
            if not hasattr(var, 'from_dict'):
                continue
            try:
                setattr(self, '_' + atr, var.__class__.from_dict(
                    property_dict[atr], self.host))
            except KeyError:
                pass  # the property_dict possesses no properties for that extension

    def ToString(self):
        """Overwrite .NET ToString method."""
        return self.__repr__()

    def __repr__(self):
        """Properties representation."""
        return 'BaseProperties'


class ModelProperties(_Properties):
    """Fairyfly Model Properties.

    This class will be extended by extensions.

    Usage:

    .. code-block:: python

        model = Model(list_of_shapes, list_of_boundaries)
        model.properties -> ModelProperties
        model.properties.therm -> ModeThermProperties
    """

    def to_dict(self, include=None):
        """Convert properties to dictionary.

        Args:
            include: A list of keys to be included in dictionary.
                If None all the available keys will be included.
        """
        base = {'type': 'ModelProperties'}
        attr = include if include is not None else self._extension_attributes
        for atr in attr:
            var = getattr(self, atr)
            if not hasattr(var, 'to_dict'):
                continue
            try:
                base.update(var.to_dict())  # no abridged dictionary for model
            except Exception as e:
                import traceback
                traceback.print_exc()
                raise Exception('Failed to convert {} to a dict: {}'.format(var, e))
        return base

    def apply_properties_from_dict(self, data):
        """Apply extension properties from a Model dictionary to the host Model.

        Args:
            data: A dictionary representation of an entire fairyfly-core Model.
        """
        for atr in self._extension_attributes:
            if atr not in data['properties'] or data['properties'][atr] is None:
                continue
            var = getattr(self, atr)
            if var and not hasattr(var, 'apply_properties_from_dict'):
                continue
            try:
                var.apply_properties_from_dict(data)
            except Exception as e:
                import traceback
                traceback.print_exc()
                raise Exception(
                    'Failed to apply {} properties to the Model: {}'.format(atr, e))

    def _check_for_extension(self, extension_name, detailed=False):
        """Check the validity of the model for a specific extension.

        Args:
            detailed: Boolean for whether the returned object is a detailed list of
                dicts with error info or a string with a message. (Default: False).
            extension_name: Text for the name of the extension to be checked.
                This value should always be lowercase to match the name of the
                extension package. Some common fairyfly extension names that can
                be input here if they are installed include:

                * therm
        """
        msgs = []
        for atr in self._extension_attributes:
            if extension_name == atr:
                check_msg = None
                try:
                    var = getattr(self, atr)
                except AttributeError as e:
                    raise ImportError(
                        'Extension for {} is not installed or has not been set up '
                        'for model validation.\n{}'.format(var, e))
                if not hasattr(var, 'check_for_extension'):
                    raise NotImplementedError(
                        'Extension for {} does not have validation routines.'.format(var))
                try:
                    check_msg = var.check_for_extension(
                        raise_exception=False, detailed=detailed)
                    if detailed and check_msg is not None:
                        msgs.append(check_msg)
                    elif check_msg != '':
                        f_msg = 'Attributes for {} are invalid.\n{}'.format(atr, check_msg)
                        msgs.append(f_msg)
                except Exception as e:
                    import traceback
                    traceback.print_exc()
                    raise Exception('Failed to check_for_extension '
                                    'for {}: {}'.format(var, e))
        return msgs

    def _check_all_extension_attr(self, detailed=False, all_ext_checks=False):
        """Check the attributes of all extensions.

        This method should be called within the check_all method of the Model object
        to ensure that the check_all functions of any extension model properties
        are also called.

        Args:
            detailed: Boolean for whether the returned object is a detailed list of
                dicts with error info or a string with a message. (Default: False).
        """
        msgs = []
        for atr in self._extension_attributes:
            # get the extension attributes
            check_msg = None
            var = getattr(self, atr)
            # use the check_generic function if it is available
            if not all_ext_checks and hasattr(var, 'check_generic'):
                try:
                    check_msg = var.check_generic(
                        raise_exception=False, detailed=detailed)
                    if detailed and check_msg is not None:
                        msgs.append(check_msg)
                    elif check_msg != '':
                        f_msg = \
                            'Attributes for {} are invalid.\n{}'.format(atr, check_msg)
                        msgs.append(f_msg)
                except Exception as e:
                    import traceback
                    traceback.print_exc()
                    raise Exception('Failed to check_generic for {}: {}'.format(var, e))
            elif hasattr(var, 'check_all'):  # use the check_all function
                try:
                    try:
                        check_msg = var.check_all(
                            raise_exception=False, detailed=detailed)
                    except TypeError:  # no option available for detailed error message
                        check_msg = var.check_all(raise_exception=False)
                    if detailed and check_msg is not None:
                        msgs.append(check_msg)
                    elif check_msg != '':
                        f_msg = \
                            'Attributes for {} are invalid.\n{}'.format(atr, check_msg)
                        msgs.append(f_msg)
                except Exception as e:
                    import traceback
                    traceback.print_exc()
                    raise Exception('Failed to check_all for {}: {}'.format(var, e))
        return msgs

    def _check_func_from_code(self, error_code):
        """Get a check function for a specific error code that exists in an extension.

        Args:
            error_code: Text for the error code for which the check will be performed.
                This can be the value under the "code" key in the dictionary of
                the validation error whenever the detailed option is used.
        """
        for atr in self._extension_attributes:
            var = getattr(self, atr)
            if hasattr(var, 'ERROR_MAP'):
                err_map = getattr(var, 'ERROR_MAP')
                try:
                    check_func = err_map[error_code]
                    check_func = getattr(var, check_func)
                    return check_func
                except KeyError:  # not the correct extension for the code
                    pass

    def __repr__(self):
        """Properties representation."""
        return 'ModelProperties: {}'.format(self.host.display_name)


class ShapeProperties(_Properties):
    """Fairyfly Shape Properties.

    This class will be extended by extensions.

    Usage:

    .. code-block:: python

        shape = Shape('South Bedroom Wall', geometry)
        shape.properties -> ShapeProperties
        shape.properties.therm -> ShapeThermProperties
    """

    def to_dict(self, abridged=False, include=None):
        """Convert properties to dictionary.

        Args:
            abridged: Boolean to note whether the full dictionary describing the
                object should be returned (False) or just an abridged version (True).
                Default: False.
            include: A list of keys to be included in dictionary. If None all
                the available keys will be included.
        """
        base = {'type': 'ShapeProperties'} if not abridged else \
            {'type': 'ShapePropertiesAbridged'}
        base = self._add_extension_attr_to_dict(base, abridged, include)
        return base

    def reset_to_default(self):
        """Reset the extension properties assigned at the level of this Shape to default.
        """
        self._reset_extension_attr_to_default()

    def __repr__(self):
        """Properties representation."""
        return 'ShapeProperties: {}'.format(self.host.display_name)


class BoundaryProperties(_Properties):
    """Fairyfly Boundary Properties.

    This class will be extended by extensions.

    Usage:

    .. code-block:: python

        boundary = Boundary(geometry)
        boundary.properties -> BoundaryProperties
        boundary.properties.therm -> BoundaryThermProperties
    """

    def to_dict(self, abridged=False, include=None):
        """Convert properties to dictionary.

        Args:
            abridged: Boolean to note whether the full dictionary describing the
                object should be returned (False) or just an abridged version (True).
                Default: False.
            include: A list of keys to be included in dictionary.
                If None all the available keys will be included.
        """
        base = {'type': 'BoundaryProperties'} if not abridged else \
            {'type': 'BoundaryPropertiesAbridged'}
        base = self._add_extension_attr_to_dict(base, abridged, include)
        return base

    def reset_to_default(self):
        """Reset the extension properties assigned to this Boundary to default.
        """
        self._reset_extension_attr_to_default()

    def __repr__(self):
        """Properties representation."""
        return 'BoundaryProperties: {}'.format(self.host.display_name)
