"""PDF credentials lib tests."""

import os
import shutil
import tempfile

from django.test import override_settings
from django.urls import reverse

from kalabash.admin import factories
from kalabash.core import models as core_models

from kalabash.lib.tests import KbashAPITestCase
from kalabash.lib.exceptions import InternalError

import kalabash.pdfcredentials.lib as lib
from subprocess import Popen, PIPE


class PDFCredentialsLibTestCase(KbashAPITestCase):

    @classmethod
    def setUpTestData(cls):  # NOQA:N802
        """Create test data."""
        super().setUpTestData()
        factories.populate_database()

    def tearDown(self):
        """Reset test env."""
        shutil.rmtree(self.workdir)

    def _create_account(self, username, expected_status=201):
        url = reverse("v2:account-list")
        data = {
            "username": f"{username}",
            "role": "StandardUsers",
            "mailbox": {"use_domain_quota": True},
            "password": "Toto12345",
            "language": "fr",
        }
        resp = self.client.post(url, data, format="json")
        self.assertEqual(resp.status_code, expected_status)
        return data

    def test_storage_dir_setting(self):
        """Test multiple possibilities with storage_dir setup"""
        self.set_global_parameter("storage_dir", "/I_DONT_EXIST")
        with self.assertRaises(InternalError):
            lib.init_storage_dir()
        self.set_global_parameter("storage_dir", "/root")
        with self.assertRaises(InternalError):
            lib.init_storage_dir()
        self.set_global_parameter("storage_dir", self.workdir)
        self.assertIsNone(lib.init_storage_dir())

    def test_pdf_decryption(self):
        """Test that PDFs are decrypted."""
        username = "toto1818@test.com"
        self._create_account(username)
        fname = os.path.join(self.workdir, "{}.pdf".format(username))
        self.assertTrue(os.path.exists(fname))
        filebuff = lib.decrypt_file(fname)
        self.assertIn(
            "application/pdf",
            Popen("/usr/bin/file -b --mime -", shell=True, stdout=PIPE, stdin=PIPE)
            .communicate(filebuff)[0]
            .strip()
            .decode(),
        )
        with open(fname, "r") as file:
            with self.assertRaises(UnicodeDecodeError):
                Popen(
                    "/usr/bin/file -b --mime -", shell=True, stdout=PIPE, stdin=PIPE
                ).communicate(file.read(1024))[0].strip()
