from patch.include import *


@app_context(commit=True)
def set_next_time_update():
    """
    Для тестирования патча: ( cd /opt/eva-app; python3 -m patch.202407120907_set_next_time_update )
    Здесь можно работать с моделями через models.CmfTask и т.д.
    Для прогрессбара используйте:
    for task in tqdm(models.CmfTask.list()):
        ...
    """
    print('Запуск патча set_next_time_update')
    limit = 100
    offset = 0

    with cmfutil.disable_acl(), cmfutil.disable_notify():
        while True:
            filter = [
                ['next_time_update', '=', 'NULL'],
                ['current', '=', True],
                ['stop_time', '=', 'NULL'],
            ]

            slice = [offset, offset + limit]
            fields = ['next_time_update']

            cycles = models.CmfSDeskSlaCycle.list(
                filter=filter,
                slice=slice,
                fields=fields,
            )

            if not cycles:
                break

            for cycle in cycles:
                cycle.next_time_update.set_now()
                cycle.next_time_update.value = models.CmfCalendar.get_sla_cycle_next_time_update(cycle.sla_goal.calendar, cycle.next_time_update.value)
                cycle.calendar_paused = models.CmfCalendar.get_sla_cycle_calendar_paused(cycle.sla_goal.calendar, cycle.next_time_update.value)
                cycle.save(only_data=True)

            commit_all_ds()

            offset += limit

if __name__ == "__main__":
    set_next_time_update()
