import uuid

RETRIEVE = 'retrive'
OPTIONAL = 'optional'


class BasicJsonHelper:
    def __init__(self, data):
        self.attributes = []
        self.extras = {}
        self.data = data

    def to_json(self):
        out = []
        for d in self.data:
            result = {}
            # add basic attributes
            for attribute in self.attributes:
                if not hasattr(d, attribute):
                    continue
                value = getattr(d, attribute)
                if value is None:
                    continue
                if isinstance(value, uuid.UUID):
                    value = str(value)
                result[attribute] = value
            out.append(result)
            # add extra rules
            for extra_key in self.extras:
                if self.extras[extra_key][OPTIONAL](d):
                    result[extra_key] = self.extras[extra_key][RETRIEVE](d)

        return out

    def add_attributes(self, attributes):
        self.attributes.extend(attributes)
        return self

    def add_extra(self, key_name, retrieve_function, optional=lambda x: True):
        self.extras[key_name] = {RETRIEVE: retrieve_function, OPTIONAL: optional}
        return self
