import axipy
from pathlib import Path
from typing import Tuple

def _create_tables(dt: axipy.DialogTask, table: axipy.Table, folder: Path) -> Tuple[bool, int]:
    n = 0
    for item in table.items():
        new_table_path = str(folder / (table.name + str(item.id) + '.tab'))
        destination = axipy.provider_manager.tab.get_destination(new_table_path, table.schema)
        destination.export([item])
        n += 1
        dt.message = f'Записей экспортировано: {n}'
        if dt.is_canceled:
            return False, n
    return True, n

try:
    res = axipy.prompt_item("Выберите таблицу", "Сохранение строк", items=[table.name for table in axipy.data_manager.tables])
    if res:
        folder = axipy.select_folder_dialog()
        if folder:
            table = axipy.data_manager[res]
            dialog_task = axipy.DialogTask(_create_tables, title="Экспорт записей", cancelable=True, delayed=False)
            result = dialog_task.run_and_get(table, folder)            
            if result[0]:
                axipy.Notifications.push("Экспорт записей", f"Экспорт завершён.\nЭкспортировано {result[1]} записей.", axipy.Notifications.Information)
            else:
                axipy.Notifications.push("Экспорт записей", f"Экспорт прерван пользователем.\nЭкспортировано {result[1]} записей.", axipy.Notifications.Information)
except Exception as e:
    axipy.Notifications.push("Экспорт записей", f"Произошла ошибка при выполнении:\n{str(e)}", axipy.Notifications.Warning)