import directory from 'api2/directory';

const FinalStatuses = [
    'success',
    'failed',
];

export default function pollStatus(path, options, period = 5000) {
    return new Promise(resolve => {
        let poll = () => {
            directory
                .send('GET', path, options)
                .then(({ ok, body }) => {
                    if (ok && FinalStatuses.includes(body.status)) {
                        resolve({ ok: body.status === 'success', body });
                    } else {
                        setTimeout(poll, period);
                    }
                })
                .catch(() => {
                    setTimeout(poll, period);
                });
        };

        poll();
    });
}
