import Polling from '@connect/polling';
import directory from 'api2/directory';
import { BalanceStore } from 'lib2/stores';

const BalancePolling = new Polling(() => {
    const currentBalance = BalanceStore.get('balance');

    return directory
        .send('GET', '/v11/subscription/', {
            query: {
                mode: 'after_pay',
            },
        })
        .then(({ ok, body }) => {
            if (ok && currentBalance !== body.balance) {
                BalanceStore.mergeState(body);

                return BalancePolling.stop();
            }
        })
        .catch(() => {
            // ignore
        });
}, counter => {
    if (counter < 5) {
        return 2000;
    }

    if (counter < 20) {
        return 10000;
    }

    return 30000;
});

export default window.ya.connect.BalancePolling = BalancePolling;
