const cm = require("../common.js");
const g = require("../geocoding.js");
const c = require("./credentials.js");        // Specifies the credentials APP_ID, APP_CODE

cm.config({
    app_id: c.APP_ID,
    app_code: c.APP_CODE,
    rps: {
        gc: 1,
        rgc:10
    }
});

test('Correct address', async () => {
    expect.assertions(1);
    const res = await g.geocode("Avenue des champs elysees, Paris");
    expect(res.coord).toEqual([48.8714, 2.30247]);
});


test('Geocoding RPS', async () => {
    expect.assertions(1);

    const N = 5;
    jest.setTimeout(N*2000); // 2x more time than needed

     let ps = [];
    const t0 = new Date().getTime();

    for (let i = 0; i < N; i++) {
        const p = g.geocode("Avenue des champs elysees, Paris");
        ps.push(p);
    }
    await Promise.all(ps);

    const t1 = new Date().getTime();
    const delta = t1-t0;
    console.log(`${N} geocodes in ${delta} ms`);
    //RPS 1 * N = N * 1,000 ms
    expect(delta).toBeGreaterThan(N * 900);
});



test("Unknown address", async () => {
    expect.assertions(1);
    try {
        await g.geocode("gjgdfdlkjfs");
    } catch (e) {
        expect(e).toEqual(new Error("Geocode Address not found: gjgdfdlkjfs"));
    }
});

test('Reverse Geocode', async () => {
    expect.assertions(1);
    const res = await g.reverseGeocode([48.8583701, 2.2944813]);
    expect(res.location.Address.Label).toEqual("75007 Paris, France");
});



test('Reverse Geocoding RPS', async () => {
    expect.assertions(1);

    const N = 10;
    jest.setTimeout(2* N*1000/10); // 2x more time than needed

     let ps = [];
    const t0 = new Date().getTime();

    for (let i = 0; i < N; i++) {
        const p =  g.reverseGeocode([48.8583701, 2.2944813]);
        ps.push(p);
    }
    await Promise.all(ps);

    const t1 = new Date().getTime();
    const delta = t1-t0;
    console.log(`${N} reverse geocodes in ${delta} ms`);
    //RPS 10
    expect(delta).toBeGreaterThan(N * 500/10);
});
