from ..exceptions import RequiredFieldIsMissing
from .. import schema


class DomainObjectField(object):
    DEFAULT_SCHEMA_TYPE = schema.TYPE.ANY

    # The same trick as in django model fields
    creation_counter = 0

    def __init__(self, name=None, schema_type=None, null=False):
        self.name = name
        self.schema_type = schema_type or self.DEFAULT_SCHEMA_TYPE
        self.null = null

        self.creation_counter = DomainObjectField.creation_counter
        DomainObjectField.creation_counter += 1

    def __meta_init__(self, class_name, attribute_name):
        self.name = self.name or attribute_name

    def translate_lookup(self, nested, value, source_field):
        return self.name, value

    @property
    def schema(self):
        return {
            'type': self.schema_type,
        }

    def validate(self, value):
        if value is None and not self.null:
            raise RequiredFieldIsMissing(data=self.name)

    def get_related_saves(self, instance):
        return ()
