from patch.include import *
from tqdm import tqdm


@app_context(commit=True)
def patch():
    """
    Для тестирования патча: ( cd /opt/crm; python3 -m patch.202205230433_tree_parent_set )
    Здесь можно работать с моделями через models.CmfTask и т.д.
    Для прогрессбара используйте:
    for task in tqdm(models.CmfTask.list()):
        ...
    """
    for active_entity_filter in models.CmfActiveEntityFilter.list(
        sys_type="tasks", fields=['parent', 'tree_nodes.tree_parent', 'tree_parent']):
        backlog = models.CmfFolder(
            name='Backlog',
            parent=active_entity_filter.parent,
            tree_parent=active_entity_filter.tree_parent,
            sys_type='backlog',
            tree_node_is_branch=True,
            orderno=100000
        )
        backlog.save(only_data=True)
        for node in active_entity_filter.tree_nodes:
            node.tree_parent = backlog
            node.perm_parent_id = backlog.id
            node.save(only_data=True)
        for child in active_entity_filter.list_children(group_by_models=False):
            if getattr(child, 'parent_id', None) == active_entity_filter.id:
                child.parent = active_entity_filter.parent
            if getattr(child, 'tree_parent_id', None) == active_entity_filter.id:
                child.tree_parent = backlog
            child.save(only_data=True)
        active_entity_filter.delete()


if __name__ == "__main__":
    patch()
