import RefDataProvider from 'bitbucket/internal/bbui/data-provider/ref';

import MockRefDataProvider from 'mocks/data-provider/ref';
import mocks from 'mocks/models';

QUnit.module('bitbucket-ref-data-provider');

QUnit.test('SPI expects user output', function(assert) {
    class TestedRefDataProvider extends RefDataProvider {
        constructor(...args) {
            super(...args);
        }
        _transform() {
            return [{}]; // not a user
        }
    }
    let mock;
    try {
        mock = new TestedRefDataProvider({
            filter: {
                repository: mocks.repository(null, 'ABC'),
                type: 'branch',
            },
        });
    } catch (e) {
        console.log(e.stack);
        throw e;
    }
    assert.throws(function() {
        mock.transform([]);
    }, 'Transform should throw on non-ref data.');
});

QUnit.test('SPI expects repository filter', function(assert) {
    assert.throws(function() {
        new RefDataProvider({ // eslint-disable-line no-new
            filter: {
                type: 'branch',
            },
        });
    }, 'ctor throws without filter');
});

QUnit.test('SPI expects type filter', function(assert) {
    assert.throws(function() {
        new RefDataProvider({ // eslint-disable-line no-new
            filter: {
                repository: mocks.repository(null, 'ABC'),
            },
        });
    }, 'ctor throws without filter');
});

QUnit.test('mock returns mock refs', function(assert) {
    const itemsPerPage = 10;
    const pages = 2;
    const mock = new MockRefDataProvider({
        nextUrl: 'meh',
        itemsPerPage,
        pages,
        filter: {
            repository: mocks.repository(null, 'ABC'),
            type: 'branch',
        },
    });

    function assertRefs(pageIndex, refs) {
        assert.strictEqual(refs.length, itemsPerPage);
        // not going to do a full validation - too brittle
        assert.strictEqual(refs[0].id, 'refs/heads/branch-' + (pageIndex * itemsPerPage + 1));
    }

    assert.expect(pages * 2);
    for(let page = 0; page < pages && !mock.reachedEnd; page++) {
        mock.fetchNext().then(assertRefs.bind(null, page));
        mock._requestPromise.resolve();
    }
});
