from .. import schema

from .plain import PlainField
from .utils import ComplexFieldAdapter


class NameField(PlainField):
    DEFAULT_SCHEMA_TYPE = schema.TYPE.OBJECT

    def __init__(self, *args, **kwargs):
        self.spec = kwargs.pop('spec', None)
        super(NameField, self).__init__(*args, **kwargs)

    def get(self, instance, owner):
        return ComplexFieldAdapter(instance.model, self.spec)

    def set(self, instance, value):
        raise AttributeError('This field does not support assignment')

    def translate_lookup(self, nested, value, source_field):
        if not nested:
            raise AttributeError
        if nested[0] not in self.spec:
            raise AttributeError(nested[0])

        return ComplexFieldAdapter.translate_lookup(
            nested, value, self.spec, source_field)

    @property
    def schema(self):
        s = {
            'type': self.schema_type,
        }
        if self.schema_type == self.DEFAULT_SCHEMA_TYPE:
            s.update({
                'additionalProperties': False,
                'properties': ComplexFieldAdapter.fields,
            })
        return s
