from unittest.mock import Mock, patch
from uuid import uuid4

from django.test import TestCase
from django.utils.lorem_ipsum import words

from newsreader.accounts.tests.factories import UserFactory
from newsreader.news.collection.exceptions import (
    StreamDeniedException,
    StreamException,
    StreamNotFoundException,
    StreamParseException,
    StreamTimeOutException,
    StreamTooManyException,
)
from newsreader.news.collection.reddit import RedditClient
from newsreader.news.collection.tests.factories import SubredditFactory

from .mocks import simple_mock


class RedditClientTestCase(TestCase):
    def setUp(self):
        self.maxDiff = None

        self.patched_read = patch("newsreader.news.collection.reddit.RedditStream.read")
        self.mocked_read = self.patched_read.start()

    def tearDown(self):
        patch.stopall()

    def test_client_retrieves_single_rules(self):
        subreddit = SubredditFactory()
        mock_stream = Mock(rule=subreddit)

        self.mocked_read.return_value = (simple_mock, mock_stream)

        with RedditClient([[subreddit]]) as client:
            for data, stream in client:
                with self.subTest(data=data, stream=stream):
                    self.assertEquals(data, simple_mock)
                    self.assertEquals(stream, mock_stream)

        self.mocked_read.assert_called_once_with()

    def test_client_catches_stream_exception(self):
        subreddit = SubredditFactory()

        self.mocked_read.side_effect = StreamException(message="Stream exception")

        with RedditClient([[subreddit]]) as client:
            for data, stream in client:
                with self.subTest(data=data, stream=stream):
                    self.assertEquals(data, None)
                    self.assertEquals(stream, None)
                    self.assertEquals(stream.rule.error, "Stream exception")
                    self.assertEquals(stream.rule.succeeded, False)

        self.mocked_read.assert_called_once_with()

    def test_client_catches_stream_not_found_exception(self):
        subreddit = SubredditFactory.create()

        self.mocked_read.side_effect = StreamNotFoundException(
            message="Stream not found"
        )

        with RedditClient([[subreddit]]) as client:
            for data, stream in client:
                with self.subTest(data=data, stream=stream):
                    self.assertEquals(data, None)
                    self.assertEquals(stream, None)
                    self.assertEquals(stream.rule.error, "Stream not found")
                    self.assertEquals(stream.rule.succeeded, False)

        self.mocked_read.assert_called_once_with()

    @patch("newsreader.news.collection.reddit.RedditTokenTask")
    def test_client_catches_stream_denied_exception(self, mocked_task):
        user = UserFactory(
            reddit_access_token=str(uuid4()), reddit_refresh_token=str(uuid4())
        )
        subreddit = SubredditFactory(user=user)

        self.mocked_read.side_effect = StreamDeniedException(message="Token expired")

        with RedditClient([(subreddit,)]) as client:
            results = [(data, stream) for data, stream in client]

        self.mocked_read.assert_called_once_with()
        mocked_task.delay.assert_called_once_with(user.pk)

        self.assertEquals(len(results), 0)

        user.refresh_from_db()
        subreddit.refresh_from_db()

        self.assertEquals(user.reddit_access_token, None)
        self.assertEquals(subreddit.succeeded, False)
        self.assertEquals(subreddit.error, "Token expired")

    def test_client_catches_stream_timed_out_exception(self):
        subreddit = SubredditFactory()

        self.mocked_read.side_effect = StreamTimeOutException(
            message="Stream timed out"
        )

        with RedditClient([[subreddit]]) as client:
            for data, stream in client:
                with self.subTest(data=data, stream=stream):
                    self.assertEquals(data, None)
                    self.assertEquals(stream, None)
                    self.assertEquals(stream.rule.error, "Stream timed out")
                    self.assertEquals(stream.rule.succeeded, False)

        self.mocked_read.assert_called_once_with()

    def test_client_catches_stream_too_many_exception(self):
        subreddit = SubredditFactory()

        self.mocked_read.side_effect = StreamTooManyException

        with RedditClient([[subreddit]]) as client:
            for data, stream in client:
                with self.subTest(data=data, stream=stream):
                    self.assertEquals(data, None)
                    self.assertEquals(stream, None)
                    self.assertEquals(stream.rule.error, "Too many requests")
                    self.assertEquals(stream.rule.succeeded, False)

        self.mocked_read.assert_called_once_with()

    def test_client_catches_stream_parse_exception(self):
        subreddit = SubredditFactory()

        self.mocked_read.side_effect = StreamParseException(
            message="Stream could not be parsed"
        )

        with RedditClient([[subreddit]]) as client:
            for data, stream in client:
                with self.subTest(data=data, stream=stream):
                    self.assertEquals(data, None)
                    self.assertEquals(stream, None)
                    self.assertEquals(stream.rule.error, "Stream could not be parsed")
                    self.assertEquals(stream.rule.succeeded, False)

        self.mocked_read.assert_called_once_with()

    def test_client_catches_long_exception_text(self):
        subreddit = SubredditFactory()
        mock_stream = Mock(rule=subreddit)

        self.mocked_read.side_effect = StreamParseException(message=words(1000))

        with RedditClient([[subreddit]]) as client:
            for data, stream in client:
                self.assertEquals(data, None)
                self.assertEquals(stream, None)
                self.assertEquals(len(stream.rule.error), 1024)
                self.assertEquals(stream.rule.succeeded, False)

        self.mocked_read.assert_called_once_with()
