# (c) cavaliba.com - tests / loader csv pipeline

import os
import tempfile

import yaml
from django.test import TestCase

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


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

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

        datalist = yaml.safe_load("""
            - classname: _pipeline
              keyname: pipeline_csvtest
              displayname: pipeline_csvtest
              is_enabled: True
              content: |
                    classname: csvtest
                    keyfield: mykey
                    csv_delimiter: ';'
                    encoding: utf-8
                    tasks: []
            """)
        load_broker(datalist=datalist, aaa={"perms": ["p_pipeline_create"]})

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

    def test_pipeline_overrides_delimiter_and_keyfield(self):
        """A ';'-delimited file with a 'mykey' column loads via the pipeline, even
        though comma is the default separator and 'keyname' isn't a column."""

        path = self._write_csv("mykey;mystring\nabc;hello\n")
        try:
            datalist = load_file_csv(filename=path, pipeline_name="pipeline_csvtest")
        finally:
            os.remove(path)

        self.assertEqual(len(datalist), 1)
        self.assertEqual(datalist[0]["classname"], "csvtest")
        self.assertEqual(datalist[0]["keyname"], "abc")

    def test_pipeline_overrides_form_schema_and_separator(self):
        """schema_name/csv_delimiter passed alongside a pipeline are ignored; the
        pipeline's own classname/csv_delimiter win."""

        path = self._write_csv("mykey;mystring\nabc;hello\n")
        try:
            datalist = load_file_csv(
                filename=path,
                pipeline_name="pipeline_csvtest",
                schema_name="othername",
                csv_delimiter=",",
            )
        finally:
            os.remove(path)

        self.assertEqual(len(datalist), 1)
        self.assertEqual(datalist[0]["classname"], "csvtest")

    def test_invalid_pipeline_name_returns_none(self):
        """An unknown pipeline_name aborts parsing entirely (returns None)."""

        path = self._write_csv("mykey;mystring\nabc;hello\n")
        try:
            datalist = load_file_csv(filename=path, pipeline_name="does_not_exist")
        finally:
            os.remove(path)

        self.assertIsNone(datalist)
