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

import yaml
import json
from .field import Field

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

# -------------
# TEXT
# -------------
class FieldText(Field):



    def get_datapoint_ui_detail(self):

        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:
                    v = ""

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

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

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

        return datapoint



    def get_datapoint_for_export(self):

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

        value = ''
        try:
            value = self.value[0]
        except:
            return value

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

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

        return value


    def merge_import(self, data):
        # no split composite !
        self.value = [data]



    def is_valid(self):
        r = super().is_valid()
        # TODO
        return r

