class TokenHelperTestCase(TestCase):
    def setUp(self):
        self.helper = TokenHelper('client_key', 'client_secret')
        self.dsf = DummySessionFactory()
        self.helper.oauth_session_cls = self.dsf

    def test_get_temporary_credentials(self):
        result = self.helper.get_temporary_credentials()
        self.assertEqual(self.dsf.args, ((), {
            'callback_uri': 'oob',
            'client_key': 'client_key',
            'client_secret': 'client_secret'
        }))

        self.assertEqual(result, ('dummy_request', 'dummy_secret'))
        self.assertTrue(self.dsf.targets[0].startswith(
            'https://models.physiomeproject.org/OAuthRequestToken?scope='))

    def test_get_authorize_url(self):
        # need temporary creds first.
        self.assertRaises(ValueError, self.helper.get_authorize_url)

        self.helper.get_temporary_credentials()
        result = self.helper.get_authorize_url()
        self.assertEqual(
            result, 'https://models.physiomeproject.org/'
            'OAuthAuthorizeToken?oauth_token=dummy_request')

    def test_get_token_credentials(self):
        self.helper.request_token = 'test_request'
        self.helper.request_secret = 'test_secret'
        self.assertRaises(ValueError, self.helper.get_token_credentials)

        self.helper.set_verifier('test_verifier')
        result = self.helper.get_token_credentials()
        self.assertEqual(self.dsf.args, ((), {
            'client_key': 'client_key',
            'client_secret': 'client_secret',
            'resource_owner_key': 'test_request',
            'resource_owner_secret': 'test_secret',
            'verifier': 'test_verifier',
        }))

        self.assertEqual(
            result, {
                'oauth_token': 'dummy_access',
                'oauth_token_secret': 'dummy_access_secret',
            })
        self.assertEqual(
            self.dsf.targets[0],
            'https://models.physiomeproject.org/OAuthGetAccessToken')
class TokenHelperTestCase(TestCase):

    def setUp(self):
        self.helper = TokenHelper('client_key', 'client_secret')
        self.dsf = DummySessionFactory()
        self.helper.oauth_session_cls = self.dsf

    def test_get_temporary_credentials(self):
        result = self.helper.get_temporary_credentials()
        self.assertEqual(self.dsf.args, ((), {
            'callback_uri': 'oob',
            'client_key': 'client_key',
            'client_secret': 'client_secret'
        }))

        self.assertEqual(result, ('dummy_request', 'dummy_secret'))
        self.assertTrue(self.dsf.targets[0].startswith(
            'https://models.physiomeproject.org/OAuthRequestToken?scope='
        ))

    def test_get_authorize_url(self):
        # need temporary creds first.
        self.assertRaises(ValueError, self.helper.get_authorize_url)

        self.helper.get_temporary_credentials()
        result = self.helper.get_authorize_url()
        self.assertEqual(result,
            'https://models.physiomeproject.org/'
                'OAuthAuthorizeToken?oauth_token=dummy_request')

    def test_get_token_credentials(self):
        self.helper.request_token = 'test_request'
        self.helper.request_secret = 'test_secret'
        self.assertRaises(ValueError, self.helper.get_token_credentials)

        self.helper.set_verifier('test_verifier')
        result = self.helper.get_token_credentials()
        self.assertEqual(self.dsf.args, ((), {
            'client_key': 'client_key',
            'client_secret': 'client_secret',
            'resource_owner_key': 'test_request',
            'resource_owner_secret': 'test_secret',
            'verifier': 'test_verifier',
        }))

        self.assertEqual(result, {
            'oauth_token': 'dummy_access',
            'oauth_token_secret': 'dummy_access_secret',
        })
        self.assertEqual(self.dsf.targets[0],
            'https://models.physiomeproject.org/OAuthGetAccessToken')
class AuthoriseApplicationDialog(QtWidgets.QDialog):
    """
    Dialog for authorising the application.
    """

    def __init__(self, parent=None):
        QtWidgets.QDialog.__init__(self, parent)
        self._ui = Ui_AuthoriseApplicationDialog()
        self._ui.setupUi(self)

        pmr_info = PMR()
        client_tokens = pmr_info.get_client_token_kwargs()
        self._helper = TokenHelper(
            client_key=client_tokens['client_key'],
            client_secret=client_tokens['client_secret'],
            site_url=pmr_info.host(),
        )

    def event(self, event):
        result = QtWidgets.QDialog.event(self, event)
        if event.type() == QtCore.QEvent.ShowToParent:
            answer = QtWidgets.QMessageBox.question(self, 'Permission Required',
                                                    'Can the MAP Client access PMR on your behalf?',
                                                    QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
                                                    QtWidgets.QMessageBox.Yes)
            if answer == QtWidgets.QMessageBox.No:
                self.reject()
            else:
                self._show_pmr()

        return result

    def _show_pmr(self):

        try:
            self._helper.get_temporary_credentials()
        except ValueError:
            logger.info('Invalid Client Credentials: Failed to retrieve temporary credentials.')
            QtWidgets.QMessageBox.information(self, 'Invalid Client Credentials',
                                              'Failed to retrieve temporary credentials.')
            return

        url = self._helper.get_authorize_url()
        webbrowser.open(url)

    def accept(self):
        if len(self._ui.tokenLineEdit.text()) > 0:
            self._register()

        QtWidgets.QDialog.accept(self)

    def _register(self):
        pmr_info = PMR()

        verifier = self._ui.tokenLineEdit.text()
        self._helper.set_verifier(verifier)

        try:
            token_credentials = self._helper.get_token_credentials()
        except ValueError:
            logger.info('Invalid Verifier: Failed to retrieve token access with verification code.')
            QtWidgets.QMessageBox.information(self, 'Invalid Verifier',
                'Failed to retrieve token access with verification code.')
            return False

        logger.debug('token: %r', token_credentials)

        pmr_info.update_token(**token_credentials)

        return True
class AuthoriseApplicationDialog(QtGui.QDialog):
    '''
    Dialog for authorising the application.
    '''


    def __init__(self, parent=None):
        '''
        Constructor
        '''
        QtGui.QDialog.__init__(self, parent)
        self._ui = Ui_AuthoriseApplicationDialog()
        self._ui.setupUi(self)

        pmr_info = info.PMRInfo()
        self._helper = TokenHelper(
            client_key=pmr_info.consumer_public_token,
            client_secret=pmr_info.consumer_secret_token,
            site_url=pmr_info.host,
        )

    def event(self, event):
        result = QtGui.QDialog.event(self, event)
        if event.type() == QtCore.QEvent.ShowToParent:
            answer = QtGui.QMessageBox.question(self, 'Permission Required',
                'Can the MAP Client access PMR on your behalf?',
                QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.Yes)
            if answer == QtGui.QMessageBox.No:
                self.reject()
            else:
                self._show_pmr()

        return result

    def _show_pmr(self):

        try:
            self._helper.get_temporary_credentials()
        except ValueError:
            logger.info('Invalid Client Credentials: Failed to retrieve temporary credentials.')
            QtGui.QMessageBox.information(self, 'Invalid Client Credentials',
                'Failed to retrieve temporary credentials.')
            return

        url = self._helper.get_authorize_url()
        webbrowser.open(url)

    def accept(self):
        if len(self._ui.tokenLineEdit.text()) > 0:
            self._register()

        QtGui.QDialog.accept(self)

    def _register(self):
        pmr_info = info.PMRInfo()

        verifier = self._ui.tokenLineEdit.text()
        self._helper.set_verifier(verifier)

        try:
            token_credentials = self._helper.get_token_credentials()
        except ValueError:
            logger.info('Invalid Verifier: Failed to retrieve token access with verification code.')
            QtGui.QMessageBox.information(self, 'Invalid Verifier',
                'Failed to retrieve token access with verification code.')
            return False

        logger.debug('token: %r', token_credentials)

        pmr_info.update_token(**token_credentials)

        return True