from yggdrasil import backwards
from yggdrasil.serialize import _default_newline
from yggdrasil.serialize.SerializeBase import SerializeBase
from yggdrasil.metaschema.datatypes.PlyMetaschemaType import PlyDict


class PlySerialize(SerializeBase):
    r"""Class for serializing/deserializing .ply file formats.

    Args:
        write_header (bool, optional): If True, headers will be added to
            serialized output. Defaults to True.
        newline (str, optional): String that should be used for new lines.
            Defaults to '\n'.

    Attributes:
        write_header (bool): If True, headers will be added to serialized
            output.
        newline (str): String that should be used for new lines.
        default_rgb (list): Default color in RGB that should be used for
            missing colors.

    """
    
    _seritype = 'ply'
    _schema_subtype_description = ('Serialize 3D structures using Ply format.')
    _schema_properties = {
        'newline': {'type': 'string',
                    'default': backwards.as_str(_default_newline)}}
    default_datatype = {'type': 'ply'}
    concats_as_str = False

    def __init__(self, *args, **kwargs):
        r"""Initialize immediately as default is only type."""
        super(PlySerialize, self).__init__(*args, **kwargs)
        self.initialized = True

    def func_serialize(self, args):
        r"""Serialize a message.

        Args:
            args: List of arguments to be formatted or numpy array to be
                serialized.

        Returns:
            bytes, str: Serialized message.

        """
        return backwards.as_bytes(self.datatype.encode_data(args, self.typedef))

    def func_deserialize(self, msg):
        r"""Deserialize a message.

        Args:
            msg: Message to be deserialized.

        Returns:
            obj: Deserialized message.

        """
        return PlyDict(self.datatype.decode_data(backwards.as_str(msg),
                                                 self.typedef))

    @classmethod
    def concatenate(cls, objects, **kwargs):
        r"""Concatenate objects to get object that would be recieved if
        the concatenated serialization were deserialized.

        Args:
            objects (list): Objects to be concatenated.
            **kwargs: Additional keyword arguments are ignored.

        Returns:
            list: Set of objects that results from concatenating those provided.

        """
        if len(objects) == 0:
            return []
        total = objects[0]
        for x in objects[1:]:
            total = total.merge(x)
        return [total]
        
    @classmethod
    def get_testing_options(cls):
        r"""Method to return a dictionary of testing options for this class.

        Returns:
            dict: Dictionary of variables to use for testing.

        """
        out = super(PlySerialize, cls).get_testing_options()
        obj = PlyDict({'vertices': [{'x': float(0), 'y': float(0), 'z': float(0)},
                                    {'x': float(0), 'y': float(0), 'z': float(1)},
                                    {'x': float(0), 'y': float(1), 'z': float(1)}],
                       'faces': [{'vertex_index': [int(0), int(1), int(2)]}]})
        out.update(objects=[obj, obj],
                   empty=dict(vertices=[], faces=[]),
                   contents=(b'ply\n'
                             + b'format ascii 1.0\n'
                             + b'comment author ygg_auto\n'
                             + b'comment File generated by yggdrasil\n'
                             + b'element vertex 6\n'
                             + b'property double x\n'
                             + b'property double y\n'
                             + b'property double z\n'
                             + b'element face 2\nproperty list uchar int vertex_index\n'
                             + b'end_header\n'
                             + b'0.0000 0.0000 0.0000\n'
                             + b'0.0000 0.0000 1.0000\n'
                             + b'0.0000 1.0000 1.0000\n'
                             + b'0.0000 0.0000 0.0000\n'
                             + b'0.0000 0.0000 1.0000\n'
                             + b'0.0000 1.0000 1.0000\n'
                             + b'3 0 1 2\n'
                             + b'3 3 4 5\n'))
        out['concatenate'] = [([], [])]
        return out
