# (c) cavaliba.com - tests / loader csv multi-value split

import os
import tempfile

from django.test import TestCase

import app_home.cache as cache
from app_data.loader import load_file_csv
from tests.helper import add_schema


class TestLoaderCsvMultivalue(TestCase):
    def setUp(self):
        cache.clear()

        add_schema(
            classname="csvtest",
            field_definition={
                "mystring": {"dataformat": "string", "displayname": "MyString"},
                "tags": {
                    "dataformat": "string",
                    "displayname": "Tags",
                    "cardinal_max": 0,
                },
            },
        )

    def _write_csv(self, content):
        fd, path = tempfile.mkstemp(suffix=".csv")
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            f.write(content)
        return path

    def test_multivalue_field_splits_on_caret(self):
        """A "^"-joined cell is split into a list only for a cardinal_max != 1 field."""

        path = self._write_csv("keyname,tags\nrow1,a^b^c\n")
        try:
            datalist = load_file_csv(filename=path, schema_name="csvtest")
        finally:
            os.remove(path)

        self.assertEqual(datalist[0]["tags"], ["a", "b", "c"])

    def test_single_value_field_with_literal_caret_not_split(self):
        """A single-value field containing a literal "^" is left as one string."""

        path = self._write_csv("keyname,mystring\nrow1,a^b^c\n")
        try:
            datalist = load_file_csv(filename=path, schema_name="csvtest")
        finally:
            os.remove(path)

        self.assertEqual(datalist[0]["mystring"], "a^b^c")

    def test_multivalue_field_without_caret_stays_untouched(self):
        """A multi-value field cell with no "^" is left as a plain string (no split
        into a single-element list)."""

        path = self._write_csv("keyname,tags\nrow1,onlyone\n")
        try:
            datalist = load_file_csv(filename=path, schema_name="csvtest")
        finally:
            os.remove(path)

        self.assertEqual(datalist[0]["tags"], "onlyone")

    def test_unknown_column_not_in_schema_left_untouched(self):
        """A CSV column with no matching schema field is passed through unchanged,
        even if it contains "^"."""

        path = self._write_csv("keyname,extra\nrow1,a^b\n")
        try:
            datalist = load_file_csv(filename=path, schema_name="csvtest")
        finally:
            os.remove(path)

        self.assertEqual(datalist[0]["extra"], "a^b")
