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

import os
import tempfile

from django.test import TestCase

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


class TestLoaderCsvActionColumn(TestCase):
    """A per-row "_action" column already flows through untouched (csv.DictReader
    preserves every header, load_instance() reads datadict.get("_action", "create")) -
    this locks in that existing behavior as a regression test."""

    def setUp(self):
        cache.clear()

        add_schema(
            classname="csvtest",
            field_definition={
                "mystring": {"dataformat": "string", "displayname": "MyString"},
            },
        )
        self.aaa = {"perms": ["p_data_admin"]}

    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 _load_and_import(self, content):
        path = self._write_csv(content)
        try:
            datalist = load_file_csv(filename=path, schema_name="csvtest")
        finally:
            os.remove(path)
        return load_broker(datalist=datalist, aaa=self.aaa)

    def test_default_action_is_create(self):
        result = self._load_and_import("keyname,mystring\nrow1,hello\n")
        self.assertEqual(result["count_ok"], 1)
        self.assertIsNotNone(
            Instance.from_keyname(classname="csvtest", keyname="row1", expand=False)
        )

    def test_action_update(self):
        add_instance(classname="csvtest", keyname="row1", fields={"mystring": "old"})
        result = self._load_and_import("keyname,mystring,_action\nrow1,new,update\n")
        self.assertEqual(result["count_ok"], 1)
        instance = Instance.from_keyname(classname="csvtest", keyname="row1", expand=True)
        self.assertEqual(instance.fields["mystring"].value[0], "new")

    def test_action_delete(self):
        add_instance(classname="csvtest", keyname="row1")
        result = self._load_and_import("keyname,_action\nrow1,delete\n")
        self.assertEqual(result["count_ok"], 1)
        self.assertIsNone(Instance.from_keyname(classname="csvtest", keyname="row1", expand=False))

    def test_action_disable_and_enable(self):
        add_instance(classname="csvtest", keyname="row1")

        result = self._load_and_import("keyname,_action\nrow1,disable\n")
        self.assertEqual(result["count_ok"], 1)
        instance = Instance.from_keyname(classname="csvtest", keyname="row1", expand=False)
        self.assertFalse(instance.is_enabled)

        result = self._load_and_import("keyname,_action\nrow1,enable\n")
        self.assertEqual(result["count_ok"], 1)
        instance = Instance.from_keyname(classname="csvtest", keyname="row1", expand=False)
        self.assertTrue(instance.is_enabled)
