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

"""
FieldText: dataformat "text", single-value only. dataformat_ext "json"/"yaml"
pretty-print the stored string as that format for display/export.

Method inventory: get_datapoint_ui_detail, get_datapoint_for_export, merge_import,
is_valid.
"""

import json

import yaml

from .field import Field

# supported dataformat_ext
# json
# yaml
# NEXT: html, markdown


# -------------
# TEXT
# -------------
class FieldText(Field):
    def get_datapoint_ui_detail(self):
        """Detail datapoint with value pretty-printed as YAML/JSON per dataformat_ext,
        falling back to the raw string on parse error."""

        datapoint = super().get_datapoint_ui_detail()

        v = ""
        if self.value:
            if len(self.value) == 1:
                v = self.value[0]
            elif len(self.value) > 1:
                try:
                    v = ", ".join([str(z) for z in self.value])
                except Exception:
                    v = ""

        if self.dataformat_ext == "yaml":
            try:
                data = yaml.safe_load(v)
                datapoint["value"] = yaml.dump(data, allow_unicode=True, sort_keys=False)
            except Exception:
                datapoint["value"] = v

        elif self.dataformat_ext == "json":
            try:
                data = yaml.safe_load(v)
                datapoint["value"] = json.dumps(data, indent=4)
            except Exception:
                datapoint["value"] = v

        # NEXT: markdown
        else:
            datapoint["value"] = v

        return datapoint

    def get_datapoint_for_export(self):
        """Return the single stored value, re-serialized as YAML/JSON per dataformat_ext
        (or an error placeholder on syntax error); "<MULTI NOT SUPPORTED>" if multi-value."""

        if self.is_multi():
            return "<MULTI NOT SUPPORTED>"

        value = ""
        try:
            value = self.value[0]
        except Exception:
            return value

        if self.dataformat_ext == "yaml":
            try:
                data = yaml.safe_load(value)
                value = yaml.dump(data, allow_unicode=True, sort_keys=False)
            except Exception:
                value = "<<YAML SYNTAX ERROR>>"

        elif self.dataformat_ext == "json":
            try:
                data = json.loads(value)
                value = json.dumps(data, indent=4, ensure_ascii=False)
            except Exception:
                value = "<<JSON SYNTAX ERROR>>"

        return value

    def merge_import(self, data):
        """Set self.value to [data] as-is (no split_composite: text is single-value)."""
        # no split composite !
        self.value = [data]

    def is_valid(self):
        """Cardinality check (super) only; no text-specific validation yet."""
        r = super().is_valid()
        # TODO
        return r
