# (c) cavaliba.com - data - field - externam

"""
FieldExternal: dataformat "external". Doesn't hold a value itself; instead points
to a local "schema" field (parent_fieldname) and names a field on the remote
instance (remote_fieldname) to resolve and inject locally, without its "_" prefix.
Resolution happens in Instance.inject_resolved_external_field().

Method inventory: get_parent_fieldname, get_remote_fieldname, get_subfields, print,
is_valid.
"""

from .field import Field


# -------------
# EXTERNAL
# -------------
class FieldExternal(Field):
    # dataformat: external
    # dataformat_ext: parent_fieldname remote_fieldname  subfield1  subfield2 ...
    # subfield# : name of resolved source schema fields to inject in local Instance

    # /!\ external FieldType fieldname **must** start with an underscore
    # the resolved schema field will be create with the same name, without underscore
    # remote_fieldname must match remote schema (with _ if another ext., without _ if schema)

    def get_parent_fieldname(self):
        """Return the local "schema" field name this external is resolved through."""
        # return self.parent_fieldname
        try:
            return self.dataformat_ext.split()[0]
        except Exception:
            return []

    def get_remote_fieldname(self):
        """Return the field name to read on the remote (parent-referenced) instance."""
        try:
            return self.dataformat_ext.split()[1]
        except Exception:
            return []

    def get_subfields(self):
        """Return the list of subfield names to inject alongside the resolved value."""
        try:
            return self.dataformat_ext.split()[2:]
        except Exception:
            return []

    def print(self):
        """Print "fieldname = value" (debug helper)."""
        try:
            # value_str = '|'.join(self.value)
            print(f"  Field: {self.fieldname} = {self.value}")
        except Exception:
            pass

    def is_valid(self):
        """Cardinality check (super) plus: fieldname must start with "_"."""
        r = super().is_valid()

        if not self.fieldname.startswith("_"):
            return False

        return r
