# (c) cavaliba.com - tests / loader csv encoding and separator

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 TestLoaderCsvEncodingSeparator(TestCase):
    def setUp(self):
        cache.clear()

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

    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_ascii_encoding(self):
        path = self._write_csv("keyname,mystring\nrow1,hello\n", encoding="ascii")
        try:
            datalist = load_file_csv(filename=path, schema_name="csvtest", encoding="ascii")
        finally:
            os.remove(path)

        self.assertEqual(datalist[0]["mystring"], "hello")

    def test_iso_8859_1_encoding(self):
        path = self._write_csv("keyname,mystring\nrow1,café\n", encoding="iso-8859-1")
        try:
            datalist = load_file_csv(filename=path, schema_name="csvtest", encoding="iso-8859-1")
        finally:
            os.remove(path)

        self.assertEqual(datalist[0]["mystring"], "café")

    def test_iso_8859_15_encoding_euro_sign(self):
        path = self._write_csv("keyname,mystring\nrow1,10€\n", encoding="iso-8859-15")
        try:
            datalist = load_file_csv(filename=path, schema_name="csvtest", encoding="iso-8859-15")
        finally:
            os.remove(path)

        self.assertEqual(datalist[0]["mystring"], "10€")

    def test_semicolon_separator(self):
        path = self._write_csv("keyname;mystring\nrow1;hello\n")
        try:
            datalist = load_file_csv(filename=path, schema_name="csvtest", csv_delimiter=";")
        finally:
            os.remove(path)

        self.assertEqual(datalist[0]["mystring"], "hello")

    def test_pipe_separator(self):
        path = self._write_csv("keyname|mystring\nrow1|hello\n")
        try:
            datalist = load_file_csv(filename=path, schema_name="csvtest", csv_delimiter="|")
        finally:
            os.remove(path)

        self.assertEqual(datalist[0]["mystring"], "hello")

    def test_default_encoding_and_separator(self):
        """No encoding/csv_delimiter given: defaults to utf-8 / comma."""

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

        self.assertEqual(datalist[0]["mystring"], "hello")
