from unittest import TestCase
from requests import HTTPError

from cognitivepy.language.spelling import SpellCheckService, SpellCheckResponse
from cognitivepy.utils import ConfigSettings

SPELL_APP_YAML = '../test_cognitive.yaml'
TEST_COG_YAML = './test_objects/test_cog.yaml'

class TestSpellCheckService(TestCase):

    def setUp(self):
        self.c = ConfigSettings(SPELL_APP_YAML)
        self.s = SpellCheckService(self.c)

    def test_service_accepts_config(self):
        # Check that the right object was called
        self.assertIsInstance(self.s, SpellCheckService)

        # Check that the Key object is correct
        self.assertEqual(self.s.key, self.c.spelling['key'])

        # Check that the API Version is correct
        self.assertEqual(self.s.api_version, self.c.spelling['api_version'])

        # Check that we can override the config file
        c = ConfigSettings(TEST_COG_YAML)
        self.s.set_config(c)
        self.assertEqual(self.s.key, c.spelling['key'])
        self.assertEqual(self.s.api_version, c.spelling['api_version'])

        self.s.set_config(self.c)

    def test_check_spelling_as_objects(self):

        # Send demo text to check spelling
        spell_check = self.s.check_spelling("Hello howre yoou?")

        # Check that spell_check is instance of SpellCheckResponse
        self.assertIsInstance(spell_check, SpellCheckResponse)

        # Check that corrected string actually corrects the text
        self.assertEqual(spell_check.corrected, 'Hello how are you?')

    def test_check_spelling_as_string(self):
        self.assertEqual(self.s.check_spelling("Hello howre yoou?", as_string=True),
                         'Hello how are you?')

    def test_check_spelling_long(self):

        text = 'By uploading data for this deemo, you agree that Microsoft may store it and use it to improve ' \
               'Microsoft services, incdfluding this API. To help protect your privacy, we take steps to de-identify ' \
               "your data and keep it secure. We wn’t publish your data or let other people use it."
        corrected = 'By uploading data for this demo, you agree that Microsoft may store it and use it to improve ' \
                    'Microsoft services, including this API. To help protect your privacy, we take steps to de-identify ' \
                    "your data and keep it secure. We won't publish your data or let other people use it."

        self.assertEqual(self.s.check_spelling(text, as_string=True),
                         corrected)

    def test_check_spelling_already_correct(self):
        text = 'This text is already correct. No correction needed!'

        self.assertEqual(self.s.check_spelling(text, as_string=True),
                         text)

    def test_check_spelling_null(self):
        with self.assertRaises(AttributeError):
            self.s.check_spelling('', as_string=True)
