# -*- coding: utf-8 -*-
#
# Copyright 2012 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.  If you modify
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.
"""Test the proxy UI."""

import qt4reactor

from PyQt4.QtCore import QObject, pyqtSignal
from twisted.internet import defer, reactor
from twisted.trial.unittest import TestCase

from ubuntu_kylin_sso.qt import proxy_dialog

# pylint: disable=E1101,W0212,


class FakeSignal(object):
    """A fake qt signal."""

    def __init__(self):
        """Create a new instance."""
        self.called = []

    def connect(self, cb):
        """Connect signals."""
        self.called.append(('connect', cb))


class FakeWidget(object):
    """A fake widget that contains text."""

    def __init__(self, object_name, called, text=''):
        """Create a new instance."""
        self.object_name = object_name
        self.called = called
        self.internal_text = text
        self.clicked = FakeSignal()

    # pylint: disable=C0103
    def setText(self, text):
        """Set the text of the widget."""
        self.internal_text = text
        if self.object_name not in self.called:
            self.called[self.object_name] = [('setText', text)]
        else:
            self.called[self.object_name].append(('setText', text))

    def text(self):
        """Return the text."""
        if self.object_name not in self.called:
            self.called[self.object_name] = [('text',)]
        else:
            self.called[self.object_name].append(('text',))
        return self.internal_text

    def setPixmap(self, pixmap):
        """Set a pixmap."""
        if self.object_name not in self.called:
            self.called[self.object_name] = [('setPixmap', pixmap)]
        else:
            self.called[self.object_name].append(('setPixmap', pixmap))

    def setVisible(self, visible):
        """Set the ui element visible."""
        if self.object_name not in self.called:
            self.called[self.object_name] = [('setVisible', visible)]
        else:
            self.called[self.object_name].append(('setVisible', visible))

    # pylint: enable=C0103


class FakeUIProxyCredsDialog(object):
    """The fake .ui for the creds dialog."""

    ui_labels = ('title_label', 'explanation_label', 'connection_label',
                   'error_label', 'username_label', 'password_label',
                   'domain_label', 'logo_label')
    ui_buttons = ('help_button', 'cancel_button', 'save_button')
    ui_entries = ('username_entry', 'password_entry')

    def __init__(self):
        """Create a new instance."""
        self.called = {}
        for name in self.ui_labels + self.ui_buttons + self.ui_entries:
            setattr(self, name, FakeWidget(name, self.called))

    # pylint: disable=C0103
    def setupUi(self, dialog):
        """Set the ui."""
        self.called['FakeUIProxyCredsDialog'] = ('setupUi', dialog)
    # pylint: enable=C0103


class FakeQIcon(object):
    """QIcon class."""

    def __init__(self):
        """Create a new instance."""
        self.called = []

    # pylint: disable=C0103
    def fromTheme(self, icon_id):
        """Return the icon with the given id."""
        self.called.append(('fromTheme', icon_id))
        return self
    # pylint: enable=C0103

    # pylint: disable=C0103
    def pixmap(self, h, w):
        """Get the pixmap with the given size."""
        self.called.append(('pixmap', h, w))
        return self
    # pylint: disable=C0103


class ProxyCredsDialogTest(TestCase):
    """Test the proxy creds dialog."""

    @defer.inlineCallbacks
    def setUp(self):
        """Set tests."""
        yield super(ProxyCredsDialogTest, self).setUp()
        self.patch(proxy_dialog, 'Ui_ProxyCredsDialog',
                   FakeUIProxyCredsDialog)
        self.icon = FakeQIcon()
        self.patch(proxy_dialog, 'QIcon', self.icon)

    def test_set_labels(self):
        """Ensure the correct labels are used."""
        dialog = proxy_dialog.ProxyCredsDialog()
        for label in dialog.ui.ui_labels:
            self.assertIn(label, dialog.ui.called, label)

    def test_set_buttons(self):
        """Ensure that buttons are set."""
        dialog = proxy_dialog.ProxyCredsDialog()
        for label in dialog.ui.ui_buttons:
            self.assertIn(label, dialog.ui.called)
        # assert that the clicked was set
        self.assertIn(('connect', dialog._on_save_clicked),
                      dialog.ui.save_button.clicked.called)
        self.assertIn(('connect', dialog._on_cancel_clicked),
                      dialog.ui.cancel_button.clicked.called)

    def test_domain_empty(self):
        """Test that if the domain is not passed we set ''"""
        dialog = proxy_dialog.ProxyCredsDialog()
        self.assertIn('domain_label', dialog.ui.called)
        self.assertIn(('setText', ''), dialog.ui.called['domain_label'])

    def test_domain_not_empty(self):
        """Test that we do set the domain."""
        domain = '192.168.1.100'
        dialog = proxy_dialog.ProxyCredsDialog(domain=domain)
        self.assertIn('domain_label', dialog.ui.called)
        self.assertIn(('setText', domain), dialog.ui.called['domain_label'])

    @defer.inlineCallbacks
    def test_retry_present_creds(self):
        """Test that we do set the error label correctly."""
        creds = dict(username='username', password='password')
        called = []
        dialog = proxy_dialog.ProxyCredsDialog(retry=True)

        def fake_get_credentials(app_name):
            """Fake the get creds."""
            called.append(('get_credentials', app_name))
            return defer.succeed(creds)

        self.patch(dialog.keyring, 'get_credentials', fake_get_credentials)

        yield dialog._load_creds()
        self.assertIn('get_credentials', called[0])
        self.assertIn('error_label', dialog.ui.called)
        self.assertIn(('setVisible', True), dialog.ui.called['error_label'])
        self.assertIn(('setText', creds['username']),
                      dialog.ui.called['username_entry'])
        self.assertIn(('setText', creds['password']),
                      dialog.ui.called['password_entry'])

    @defer.inlineCallbacks
    def test_retry_none_creds(self):
        """Test that we do set the error label correctly."""
        called = []
        dialog = proxy_dialog.ProxyCredsDialog(retry=True)

        def fake_get_credentials(app_name):
            """Fake the get creds."""
            called.append(('get_credentials', app_name))
            return defer.succeed(None)

        self.patch(dialog.keyring, 'get_credentials', fake_get_credentials)

        yield dialog._load_creds()
        self.assertIn('get_credentials', called[0])
        self.assertIn('error_label', dialog.ui.called)
        self.assertIn(('setVisible', True), dialog.ui.called['error_label'])
        self.assertNotIn('username_entry', dialog.ui.called)
        self.assertNotIn('password_entry', dialog.ui.called)

    @defer.inlineCallbacks
    def test_retry_exception_creds(self):
        """Test that we do set the error label correctly."""
        called = []
        dialog = proxy_dialog.ProxyCredsDialog(retry=True)

        def fake_get_credentials(app_name):
            """Fake the get creds."""
            called.append(('get_credentials', app_name))
            return defer.fail(Exception('Fail test'))

        self.patch(dialog.keyring, 'get_credentials', fake_get_credentials)

        yield dialog._load_creds()
        self.assertIn('get_credentials', called[0])
        self.assertIn('error_label', dialog.ui.called)
        self.assertIn(('setVisible', True), dialog.ui.called['error_label'])
        self.assertNotIn('username_entry', dialog.ui.called)
        self.assertNotIn('password_entry', dialog.ui.called)

    def test_is_not_retry(self):
        """Test that we do set the error label correctly."""
        dialog = proxy_dialog.ProxyCredsDialog(retry=False)
        self.assertIn('error_label', dialog.ui.called)
        self.assertIn(('setVisible', False), dialog.ui.called['error_label'])

    def test_icon(self):
        """Test that we correctly set the icon."""
        dialog = proxy_dialog.ProxyCredsDialog()
        self.assertIn(('fromTheme', 'gtk-dialog-authentication'),
                      self.icon.called)
        self.assertIn(('pixmap', 48, 48),
                      self.icon.called)
        self.assertIn(('setPixmap', self.icon),
                      dialog.ui.called['logo_label'])

    def test_on_cancel_clicked(self):
        """Test the on cancel clicked event."""
        dialog = proxy_dialog.ProxyCredsDialog()
        called = []

        def fake_done(result):
            """Fake the done method."""
            called.append(('done', result))

        self.patch(dialog, 'done', fake_done)

        dialog._on_cancel_clicked()
        self.assertIn(('done', proxy_dialog.USER_CANCELLATION), called)

    def assert_save_button(self, set_creds_callback, result_number):
        """Test the save button execution."""
        dialog = proxy_dialog.ProxyCredsDialog()
        called = []

        def fake_done(result):
            """Fake the done method."""
            called.append(('done', result))

        self.patch(dialog, 'done', fake_done)

        def fake_set_credentials(app_name, creds):
            """Fake an error."""
            called.append(('set_credentials', app_name, creds))
            return set_creds_callback()

        self.patch(dialog.keyring, 'set_credentials', fake_set_credentials)

        dialog._on_save_clicked()
        self.assertIn(('done', result_number), called)

    def test_on_save_clicked_exception(self):
        """Test that the exception is handled correctly."""
        set_creds_cb = lambda: defer.fail(Exception())
        result_number = proxy_dialog.EXCEPTION_RAISED
        self.assert_save_button(set_creds_cb, result_number)

    def test_on_save_clicked_correct(self):
        """Test that we do save the creds."""
        set_creds_cb = lambda: defer.succeed(True)
        result_number = proxy_dialog.USER_SUCCESS
        self.assert_save_button(set_creds_cb, result_number)


class FakeArgs(object):
    """Some fake args."""

    def __init__(self, domain='', retry=False):
        """Create a new instance."""
        self.domain = domain
        self.retry = retry


class FakeCredsDialog(QObject):
    """A fake dialog."""

    finished = pyqtSignal(int)

    def __init__(self, called, code):
        """Create a new instance."""
        super(FakeCredsDialog, self).__init__()
        self.domain = None
        self.retry = None
        self.called = called
        self.return_code = code

    def __call__(self, domain, retry):
        """Fake init."""
        self.domain = domain
        self.retry = retry
        return self

    def show(self):
        """Show the dialog."""
        self.called.append(('show',))

    def exec_(self):
        """Show the dialog."""
        self.called.append(('exec_',))
        return self.return_code


class FakeQApplication(object):
    """A fake QApplication."""

    test_instance = None

    def __init__(self, called):
        """Create a new instance."""
        self.called = called
        self.args = None
        self.code = None
        FakeQApplication.test_instance = self

    def __call__(self, args):
        """Fake construntor."""
        self.args = args

    @classmethod
    def instance(cls):
        """Return the instance."""
        return FakeQApplication.test_instance

    def exit(self, code):
        """Exit the app."""
        self.called.append(('exit', code))
        self.code = code


class MainTest(TestCase):
    """Test the main method."""

    @defer.inlineCallbacks
    def setUp(self):
        """Set the different tests."""
        yield super(MainTest, self).setUp()
        self.called = []

        self.return_code = 0
        self.dialog = FakeCredsDialog(self.called, self.return_code)
        self.patch(proxy_dialog, 'ProxyCredsDialog', self.dialog)

        self.args = FakeArgs(domain='domain', retry=False)
        self.patch(proxy_dialog, 'parse_args', lambda: self.args)

        self.exit_code = None

        self.app = FakeQApplication(self.called)

        self.patch(proxy_dialog, 'QApplication', self.app)

    def _set_old_platform(self, platform):
        """Set back the platform."""
        proxy_dialog.sys.platform = platform

    def _assert_basic_start(self):
        """Assert the common code is actually ran."""
        self.assertEqual(self.args.domain, self.dialog.domain)
        self.assertEqual(self.args.retry, self.dialog.retry)

    def test_linux_main(self):
        """Test the main method on linux."""
        old_platform = proxy_dialog.sys.platform
        proxy_dialog.sys.platform = 'linux'
        self.addCleanup(self._set_old_platform, old_platform)

        def fake_exit(code):
            """Fake sys exit."""
            self.called.append(('exit', code))

        self.patch(proxy_dialog.sys, 'exit', fake_exit)

        proxy_dialog.main()

        self._assert_basic_start()
        self.assertIn(('exec_',), self.called)
        self.assertIn(('exit', self.return_code), self.called)

    def test_windows_main(self):
        """Test the main method on windows."""
        old_platform = proxy_dialog.sys.platform
        proxy_dialog.sys.platform = 'win32'
        self.addCleanup(self._set_old_platform, old_platform)

        def fake_install():
            """Fake the reactor installation."""
            self.called.append(('install',))

        self.patch(qt4reactor, 'install', fake_install)

        def fake_start():
            """Fake reactor.start."""
            self.called.append(('run',))

        self.patch(reactor, 'run', fake_start)

        def fake_exit(code):
            """Fake the exit method."""
            self.called.append(('exit_code', code))

        self.patch(proxy_dialog, 'exit_code', fake_exit)

        proxy_dialog.main()

        self._assert_basic_start()
        self.assertIn(('show',), self.called)
        self.assertIn(('run',), self.called)

        self.dialog.finished.emit(self.return_code)
        self.assertIn(('exit_code', self.return_code), self.called)

    def test_exit_code_windows(self):
        """"Test the exit code function."""
        old_platform = proxy_dialog.sys.platform
        proxy_dialog.sys.platform = 'win32'
        self.addCleanup(self._set_old_platform, old_platform)

        def fake_stop():
            """Fake reactor.start."""
            self.called.append(('stop',))

        self.patch(reactor, 'stop', fake_stop)

        proxy_dialog.exit_code(self.return_code)
        self.assertIn(('stop',), self.called)
        self.assertIn(('exit', self.return_code), self.called)
