"""Test letsencrypt.display.completer."""
import os
import readline
import shutil
import string
import sys
import tempfile
import unittest

import mock
from six.moves import reload_module  # pylint: disable=import-error


class CompleterTest(unittest.TestCase):
    """Test letsencrypt.display.completer.Completer."""

    def setUp(self):
        self.temp_dir = tempfile.mkdtemp()

        # directories must end with os.sep for completer to
        # search inside the directory for possible completions
        if self.temp_dir[-1] != os.sep:
            self.temp_dir += os.sep

        self.paths = []
        # create some files and directories in temp_dir
        for c in string.ascii_lowercase:
            path = os.path.join(self.temp_dir, c)
            self.paths.append(path)
            if ord(c) % 2:
                os.mkdir(path)
            else:
                with open(path, 'w'):
                    pass

    def tearDown(self):
        shutil.rmtree(self.temp_dir)

    def test_complete(self):
        from letsencrypt.display import completer
        my_completer = completer.Completer()
        num_paths = len(self.paths)

        for i in range(num_paths):
            completion = my_completer.complete(self.temp_dir, i)
            self.assertTrue(completion in self.paths)
            self.paths.remove(completion)

        self.assertFalse(self.paths)
        completion = my_completer.complete(self.temp_dir, num_paths)
        self.assertEqual(completion, None)

    def test_import_error(self):
        original_readline = sys.modules['readline']
        sys.modules['readline'] = None

        self.test_context_manager_with_unmocked_readline()

        sys.modules['readline'] = original_readline

    def test_context_manager_with_unmocked_readline(self):
        from letsencrypt.display import completer
        reload_module(completer)

        original_completer = readline.get_completer()
        original_delims = readline.get_completer_delims()

        with completer.Completer():
            pass

        self.assertEqual(readline.get_completer(), original_completer)
        self.assertEqual(readline.get_completer_delims(), original_delims)

    @mock.patch('letsencrypt.display.completer.readline', autospec=True)
    def test_context_manager_libedit(self, mock_readline):
        mock_readline.__doc__ = 'libedit'
        self._test_context_manager_with_mock_readline(mock_readline)

    @mock.patch('letsencrypt.display.completer.readline', autospec=True)
    def test_context_manager_readline(self, mock_readline):
        mock_readline.__doc__ = 'GNU readline'
        self._test_context_manager_with_mock_readline(mock_readline)

    def _test_context_manager_with_mock_readline(self, mock_readline):
        from letsencrypt.display import completer

        mock_readline.parse_and_bind.side_effect = enable_tab_completion

        with completer.Completer():
            pass

        self.assertTrue(mock_readline.parse_and_bind.called)


def enable_tab_completion(unused_command):
    """Enables readline tab completion using the system specific syntax."""
    libedit = 'libedit' in readline.__doc__
    command = 'bind ^I rl_complete' if libedit else 'tab: complete'
    readline.parse_and_bind(command)

if __name__ == "__main__":
    unittest.main()  # pragma: no cover
