"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const { option: { Some, None }, Instrumentation, Tracer } = require('zipkin');
const url = require('url');
function formatRequestUrl(req) {
    const parsed = url.parse(req.originalUrl);
    return url.format({
        protocol: req.protocol,
        host: req.get('host'),
        pathname: parsed.pathname,
        search: parsed.search
    });
}
module.exports = function expressMiddleware({ tracer, serviceName, port = 0 }) {
    const instrumentation = new Instrumentation.HttpServer({ tracer, serviceName, port });
    return function zipkinExpressMiddleware(req, res, next) {
        tracer.scoped(() => {
            function readHeader(header) {
                const val = req.header(header);
                if (val != null) {
                    return new Some(val);
                }
                else {
                    return None;
                }
            }
            const id = instrumentation.recordRequest(req.method, formatRequestUrl(req), readHeader);
            /**
             * add body
             */
            if ("POST" == req.method && req.body != undefined) {
                tracer.recordBinary('http.post_body', JSON.stringify(req.body));
            }
            /**
             * store the ids in the res.locals area
             */
            res.locals.spanId = id.traceId;
            res.locals.traceId = id.spanId;
            /*
            //DONT KNOW if we need these atm, if needed uncomment the block
            //store parent id
            id._parentId.ifPresent(function (psid:string) {
              res.locals.parentId = psid;
            });
            
            //store sampled flag
            id.sampled.ifPresent(function (sampled:string) {
              res.locals.sampled = sampled ? '1' : '0';
            });
            */
            res.on('finish', () => {
                tracer.scoped(() => {
                    instrumentation.recordResponse(id, res.statusCode);
                });
            });
            next();
        });
    };
};
//# sourceMappingURL=expressMiddleware.js.map