"""Tests for certbot_dns_ispmgr.dns_ispmgr."""

import unittest

import mock
import json
import requests_mock

from certbot import errors
from certbot.compat import os
from certbot.plugins import dns_test_common
from certbot.plugins.dns_test_common import DOMAIN
from certbot.tests import util as test_util

FAKE_USER = "admin"
FAKE_PW = "password"
FAKE_ENDPOINT = "https://example.com/ispmgr"


class AuthenticatorTest(
    test_util.TempDirTestCase, dns_test_common.BaseAuthenticatorTest
):
    def setUp(self):
        super(AuthenticatorTest, self).setUp()
        self.patch_notify = mock.patch("certbot.display.util.notify")
        self.patch_notify.start()
        self.addCleanup(self.patch_notify.stop)

        from certbot_dns_ispmgr.dns_ispmgr import Authenticator

        path = os.path.join(self.tempdir, "file.ini")
        dns_test_common.write(
            {
                "ispmgr_username": FAKE_USER,
                "ispmgr_password": FAKE_PW,
                "ispmgr_endpoint": FAKE_ENDPOINT,
            },
            path,
        )

        super(AuthenticatorTest, self).setUp()
        self.config = mock.MagicMock(
            ispmgr_credentials=path, ispmgr_propagation_seconds=0
        )  # don't wait during tests

        self.auth = Authenticator(self.config, "ispmgr")

        self.mock_client = mock.MagicMock()
        # _get_ispmgr_client | pylint: disable=protected-access
        self.auth._get_ispmgr_client = mock.MagicMock(return_value=self.mock_client)

    def test_perform(self):
        self.auth.perform([self.achall])

        expected = [
            mock.call.add_txt_record(
                "_acme-challenge." + DOMAIN, mock.ANY
            )
        ]
        self.assertEqual(expected, self.mock_client.mock_calls)

    def test_cleanup(self):
        # _attempt_cleanup | pylint: disable=protected-access
        self.auth._attempt_cleanup = True
        self.auth.cleanup([self.achall])

        expected = [
            mock.call.del_txt_record(
                "_acme-challenge." + DOMAIN, mock.ANY
            )
        ]
        self.assertEqual(expected, self.mock_client.mock_calls)


class ISPmanagerClientTest(unittest.TestCase):
    record_name = "_acme-challenge.example.com"
    record_content = "bar"

    def setUp(self):
        from certbot_dns_ispmgr.dns_ispmgr import _ISPmanagerClient

        self.adapter = requests_mock.Adapter()

        self.client = _ISPmanagerClient(FAKE_ENDPOINT, FAKE_USER, FAKE_PW, DOMAIN)
        self.client.session.mount("https://", self.adapter)

    def test_add_txt_record(self):
        self.adapter.register_uri(
            "GET",
            requests_mock.ANY,
            [
                {"json": {"auth": "FAKE_SESSION"}}, # Login
                {"json": {"result": "OK"}},         # Add TXT
            ]
        )
        self.client.add_txt_record(self.record_name, self.record_content)

    def test_add_txt_record_fail_to_authenticate(self):
        self.adapter.register_uri(
            "GET",
            requests_mock.ANY,
            json={"error": "auth_failed"}
        )
        with self.assertRaises(errors.PluginError):
            self.client.add_txt_record(self.record_name, self.record_content)

    def test_del_txt_record(self):
        self.adapter.register_uri(
            "GET",
            requests_mock.ANY,
            [
                {"json": {"auth": "FAKE_SESSION"}}, # Login
                {"json": {"elem": [{"name": self.record_name, "type": "TXT", "key": "foo_key"}]}}, # List TXT
                {"json": {"result": "OK"}},         # Delete TXT
            ]
        )
        self.client.del_txt_record(self.record_name, self.record_content)

if __name__ == "__main__":
    unittest.main()
