from django.test import TestCase
from wagtail.rich_text import RichText
from assignments.models import Assignment
from assignments.factories import AssignmentFactory

from books.factories import BookFactory, ContentBlockFactory
from books.models.contentblock import ContentBlock
from core.logger import get_logger
from surveys.factories import SurveyFactory
from surveys.models import Survey
from users.services import create_users

logger = get_logger(__name__)


class DuplicateContentsTestCase(TestCase):
    def setUp(self) -> None:
        logger.debug("start setUp")
        create_users()
        logger.debug("after create_users")
        _, _, self.module, chapter, _ = BookFactory.create_default_structure()
        self.assignment = AssignmentFactory(assignment="Assignment", title="Hello")
        survey = SurveyFactory(title="Survey Title")
        rich_text = RichText("Hallo")
        logger.debug("before factory")
        self.content_block = ContentBlockFactory.create(
            parent=chapter,
            module=self.module,
            title="Another content block",
            type="task",
            contents__0__text_block__text=rich_text,
            contents__1__assignment__assignment_id=self.assignment,
            contents__2__survey__survey_id=survey,
        )

    def test_duplicate_entities(self):
        logger.debug("start test")
        self.assertEqual(
            self.content_block.contents[1].value["assignment_id"], self.assignment
        )
        self.assertEqual(
            self.content_block.contents[1].value["assignment_id"].title, "Hello"
        )
        self.assertEqual(Assignment.objects.count(), 1)
        self.assertEqual(Survey.objects.count(), 1)
        logger.debug("before duplicate")
        self.content_block.duplicate_attached_entities()
        logger.debug("after duplicate")
        self.assertEqual(Assignment.objects.count(), 2)
        self.assertEqual(Survey.objects.count(), 2)
        new_assignment = Assignment.objects.latest("id")
        new_survey = Survey.objects.latest("id")
        content_block = ContentBlock.objects.get(id=self.content_block.id)
        self.assertEqual(len(content_block.contents), 3)
        self.assertEqual(
            content_block.contents[1].value["assignment_id"], new_assignment
        )
        self.assertEqual(content_block.contents[2].value["survey_id"], new_survey)
