import request from './request';

let serverBox = (serverGen, port = 0) => async (handler) => {
    let server = await serverGen(port);

    let realPort = server.address().port;

    let send = async (opts, data) => {
        return await request(_default({
            host: '127.0.0.1',
            port: realPort,
            method: 'GET'
        }, opts), data);
    }

    if (handler) {
        await handler(server, send);
    }

    let close = () => new Promise((r) => server.close(r));

    await close();
}

let _default = (def, opts) => {
    for(let name in opts){
        def[name] = opts[name];
    }
    return def;
}

module.exports = serverBox;