from wagtail.models import PageManager
from typing import TYPE_CHECKING

from core.logger import get_logger

if TYPE_CHECKING:
    from books.models import ContentBlock

logger = get_logger(__name__)

class ContentBlockManager(PageManager):
    def duplicate(self, content_block: "ContentBlock", user):
        try:
            new_content_block = self.model(
                user_created=True,
                owner=user,
                contents=content_block.contents,
                title=f'{content_block.title} (Kopie)',
                type=content_block.type,
            )
            content_block.add_sibling(instance=new_content_block, pos='left')
            revision = new_content_block.save_revision()
            revision.publish()
            new_content_block.save()
            return new_content_block
        except Exception as e:
            logger.warn(e)
