import {fork} from 'child_process';
import tape from 'tape';
import _test from 'tape-promise';
import http from 'http';

const tapetest = _test(tape);

tapetest('service', async function testService(t) {
    const server = fork('build/service.js'),
        connstring = 'http://localhost:8080';

    try {
        await waitPro();
        const data = await requestPro(connstring + '/');
        console.log('data', data);
    }
    catch(e) {
        console.log('error somewhere', e);
        t.fail('error somewhere');
    }

    server.kill();
    t.end();
});


function waitPro(n = 1000) {
    return new Promise(function pro(resolve, reject) {
        setTimeout(resolve, n);
    });
}
function requestPro(reqopts, data) {
    return new Promise(function prot(resolve, reject) {
        try {
            let req = http.request(reqopts, function received(resp) {
                let str = '';
                resp.on('data', function p(part) {
                    str += part;
                });
                resp.on('end', function done() {
                    if( resp.statusCode >= 400 && resp.statusCode <= 599 ) {
                        reject(str);
                    }
                    else {
                        resolve(str);
                    }
                });
            });
            if( data ) {
                req.write(data);
            }
            req.end();
        }
        catch(e) {
            reject(e);
        }
    });
}