
from .models.custom_document import CustomDocument


def migrate_documents_to_custom_document_model(dryrun=False):
    try:
        from wagtail.documents.models import Document
        all_documents = Document.objects.all()
    except Exception as e:
        # new databases do not have the table for the standart wagtail documents there fore the migration is not
        # necessary. Mainly
        return
    print(f"Found {all_documents.count()} Documents")

    for document in all_documents:
        tags = document.title.replace(':', '').split(' ')

        if dryrun:
            print('')
            print(document.title)
            print(tags)
            print(document.created_at)
            print(document.url)
            print(document.file)
            print(document.uploaded_by_user)

        else:
            print('')
            new_document, created = CustomDocument.objects.get_or_create(title=document.title)
            new_document.display_text = document.title
            new_document.created_at = document.created_at
            new_document.uploaded_by_user = document.uploaded_by_user
            new_document.file = document.file
            new_document.collection = document.collection
            new_document.file_hash = document.file_hash
            new_document.file_size = document.file_size

            new_document.save()
            if created:
                print(f'Created New Document {new_document}')
            else:
                print(f'Udated document {document}')
