from patch.include import *
from tqdm import tqdm


@app_context(commit=True)
def patch():
    """
    Здесь можно работать с моделями через models.CmfTask и т.д.
    Для прогрессбара используйте:
    for task in tqdm(models.CmfTask.list()):
        ...
    """
    comments = models.CmfComment.list(filter=[['parent_id', 'LIKE', 'CmfChatTopic%'],
                                               ['channel_message_id', '!=', None]],
                                       fields=['parent_id', 'cmf_author_id',
                                               'cmf_created_at',
                                               'cmf_modified_at',
                                               'channel_message_id', 'deal_id',
                                               'cache_cmf_author_login', 'cache_cmf_author_name',
                                               'cache_cmf_author_code', 'views', 'text'], order_by=['cmf_created_at'])
    for comment in tqdm(comments):
        message = models.CmfChatMessage(parent=comment.parent_id, cmf_created_at=comment.cmf_created_at,
                                        cmf_modified_at=comment.cmf_modified_at, deal=comment.deal_id,
                                        cmf_author=comment.cmf_author_id, cache_cmf_author_login=comment.cache_cmf_author_login,
                                        cache_cmf_author_name=comment.cache_cmf_author_name,
                                        cache_cmf_author_code=comment.cache_cmf_author_code,
                                        views=comment.views, text=comment.text)
        message.save(only_data=True)
        channel_message = models.CmfChannelMessage.get(id=comment.channel_message_id)
        channel_message.chat_message = message
        channel_message.save(only_data=True)
        comment.delete()


if __name__ == "__main__":
    patch()
