from patch.include import *
from tqdm import tqdm
from cmf.system_data import scaffold_project_role


@app_context(commit=True)
def patch():
    """
    Для тестирования патча: ( cd /opt/eva-app; python3 -m patch.20220XXXXXXX_PATCHNAME )
    Здесь можно работать с моделями через models.CmfTask и т.д.
    Для прогрессбара используйте:
    for task in tqdm(models.CmfTask.list()):
        ...
    """
    # root_parent - это fk на проект
    fields = ['root_parent', 'parent.root_parent']
    with cmfutil.disable_acl(), cmfutil.disable_notify():
        for model in cmf.models.CmfEntity.iter_subclasses():
            print(f'Process {model}')
            while (obj_list := model.list(
                    fields=fields, filter=[['root_parent_id', 'NOT LIKE', 'CmfProject:%'],['root_parent_id', '!=', None]],
                    include_deleted=True, include_templates=True, slice=[0, 1000])):
                for obj in obj_list:
                    if obj.root_parent_id and not obj.root_parent_id.value.startswith('CmfProject:'):
                        new_root_parent = None
                        if obj.parent and obj.parent.root_parent and obj.parent.root_parent_id.value.startswith('CmfProject:'):
                            new_root_parent = obj.parent.root_parent
                        obj.root_parent = new_root_parent
                        obj.save(only_data=True, emit=False, notify=False)
                commit_all_ds()
                print('1000 obj done')

if __name__ == "__main__":
    patch()

