from patch.include import *
from tqdm import tqdm


@app_context(commit=True)
def patch():
    """
    Для тестирования патча: ( cd /opt/eva-app; python3 -m patch.client_fix_choices )
    Здесь можно работать с моделями через models.CmfTask и т.д.
    Для прогрессбара используйте:
    for task in tqdm(models.CmfTask.list()):
        ...
    """
    from cmf.util.cmfutil import translit_strip
    def fix_choices(field_name, choices, length=32):
        new_choices = dict()
        for key, val in choices.items():
            new_key = translit_strip(val, sep='-', length=length)
            # Если старый ключ содержал спец символы то мы не сможем его транслитилировать
            if not new_key:
                print(f'Невозможно транслитилировать ключ {val}')
                continue
            new_choices[new_key] = val
            if key != new_key:
                models.CmfTask.bulk_update(filter=[field_name, '==', key],values={field_name:new_key})
        return new_choices

    with cmfutil.disable_acl(), cmfutil.disable_notify():
        for cust_field in tqdm(models.CmfCustField.list(filter=[['field_custom_type', '==', 'choice_str'], ['choices', '!=', None]], fields=['*'])):
            all_choices = fix_choices(cust_field.name.value, cust_field.choices.value)
            for conf in models.CmfCustFieldConfField.list(filter=[['cust_field', '==', cust_field], ['choices', '!=', None]], fields=['*']):
                new_choices = fix_choices(conf.name.value, conf.choices.value)
                all_choices.update(new_choices)
                conf.choices=new_choices
                conf.save()
            cust_field.choices = all_choices
            cust_field.save()
            cmf_commit()
    models.CmfTask.custom_field_sync()


if __name__ == "__main__":
    patch()
