# (c) cavaliba.com - tests / view import tool - yaml/json file section

import json

from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, override_settings
from django.urls import reverse

import app_home.cache as cache
from app_data.data import Instance
from tests import helper


class ViewImportFileTest(TestCase):
    def setUp(self):
        cache.clear()
        helper.add_admin_user(login="unittest")
        helper.add_schema(
            classname="filetest",
            field_definition={
                "mystring": {"dataformat": "string", "displayname": "MyString"},
            },
        )

    def _post_file(self, filename, content, submit, follow=False):
        data = {
            "mode": "file",
            "file": SimpleUploadedFile(filename, content.encode("utf-8")),
            "pipeline": "",
            "submit": submit,
        }
        return self.client.post(reverse("app_data:data_import"), data, follow=follow)

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_yaml_file_verify(self):
        content = "- classname: filetest\n  keyname: row1\n  mystring: hello\n"
        response = self._post_file("data.yml", content, "verify")
        self.assertEqual(response.status_code, 200)
        rendered = [str(m) for m in response.context["messages"]]
        self.assertTrue(any("Check ok" in m for m in rendered))

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_yaml_file_import(self):
        content = "- classname: filetest\n  keyname: row2\n  mystring: hello\n"
        response = self._post_file("data.yaml", content, "import")
        self.assertEqual(response.status_code, 302)
        instance = Instance.from_keyname(classname="filetest", keyname="row2", expand=False)
        self.assertIsNotNone(instance)

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_json_file_import(self):
        content = json.dumps([{"classname": "filetest", "keyname": "row3", "mystring": "hi"}])
        response = self._post_file("data.json", content, "import")
        self.assertEqual(response.status_code, 302)
        instance = Instance.from_keyname(classname="filetest", keyname="row3", expand=False)
        self.assertIsNotNone(instance)

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_unsupported_extension_rejected(self):
        response = self._post_file("data.txt", "irrelevant", "verify")
        self.assertEqual(response.status_code, 200)
        rendered = [str(m) for m in response.context["messages"]]
        self.assertTrue(any("unsupported file type" in m for m in rendered))
