///<reference path="..\typings\globals\node\index.d.ts" />
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var url = require("url");
var ContractsModule = require("../Library/Contracts");
var Util = require("../Library/Util");
var RequestResponseHeaders = require("../Library/RequestResponseHeaders");
var RequestParser = require("./RequestParser");
/**
 * Helper class to read data from the requst/response objects and convert them into the telemetry contract
 */
var ServerRequestParser = (function (_super) {
    __extends(ServerRequestParser, _super);
    function ServerRequestParser(request) {
        _super.call(this);
        if (request) {
            this.method = request.method;
            this.url = this._getAbsoluteUrl(request);
            this.startTime = +new Date();
            this.rawHeaders = request.headers || request.rawHeaders;
            this.socketRemoteAddress = request.socket && request.socket.remoteAddress;
            this.userAgent = request.headers && request.headers["user-agent"];
            this.sourceIKeyHash =
                request.headers && request.headers[RequestResponseHeaders.sourceInstrumentationKeyHeader];
            if (request.connection) {
                this.connectionRemoteAddress = request.connection.remoteAddress;
                this.legacySocketRemoteAddress = request.connection["socket"] && request.connection["socket"].remoteAddress;
            }
        }
    }
    ServerRequestParser.prototype.onError = function (error, properties, ellapsedMilliseconds) {
        this._setStatus(undefined, error, properties);
    };
    ServerRequestParser.prototype.onResponse = function (response, properties, ellapsedMilliseconds) {
        this._setStatus(response.statusCode, undefined, properties);
        if (ellapsedMilliseconds) {
            this.duration = ellapsedMilliseconds;
        }
    };
    ServerRequestParser.prototype.getRequestData = function () {
        var requestData = new ContractsModule.Contracts.RequestData();
        requestData.httpMethod = this.method;
        requestData.id = Util.newGuid();
        requestData.name = this.method + " " + url.parse(this.url).pathname;
        requestData.startTime = (new Date(this.startTime)).toISOString();
        requestData.url = this.url;
        requestData.source = this.sourceIKeyHash;
        requestData.duration = Util.msToTimeSpan(this.duration);
        requestData.responseCode = this.statusCode ? this.statusCode.toString() : null;
        requestData.success = this._isSuccess();
        requestData.properties = this.properties;
        var data = new ContractsModule.Contracts.Data();
        data.baseType = "Microsoft.ApplicationInsights.RequestData";
        data.baseData = requestData;
        return data;
    };
    ServerRequestParser.prototype.getRequestTags = function (tags) {
        // create a copy of the context for requests since client info will be used here
        var newTags = {};
        for (var key in tags) {
            newTags[key] = tags[key];
        }
        // don't override tags if they are already set
        newTags[ServerRequestParser.keys.locationIp] = tags[ServerRequestParser.keys.locationIp] || this._getIp();
        newTags[ServerRequestParser.keys.sessionId] = tags[ServerRequestParser.keys.sessionId] || this._getId("ai_session");
        newTags[ServerRequestParser.keys.userId] = tags[ServerRequestParser.keys.userId] || this._getId("ai_user");
        newTags[ServerRequestParser.keys.userAgent] = tags[ServerRequestParser.keys.userAgent] || this.userAgent;
        newTags[ServerRequestParser.keys.operationName] = tags[ServerRequestParser.keys.operationName] || this.method + " " + url.parse(this.url).pathname;
        return newTags;
    };
    ServerRequestParser.prototype._getAbsoluteUrl = function (request) {
        if (!request.headers) {
            return request.url;
        }
        var encrypted = request.connection ? request.connection.encrypted : null;
        var requestUrl = url.parse(request.url);
        var pathName = requestUrl.pathname;
        var search = requestUrl.search;
        var absoluteUrl = url.format({
            protocol: encrypted ? "https" : "http",
            host: request.headers.host,
            pathname: pathName,
            search: search
        });
        return absoluteUrl;
    };
    ServerRequestParser.prototype._getIp = function () {
        // regex to match ipv4 without port
        // Note: including the port would cause the payload to be rejected by the data collector
        var ipMatch = /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/;
        var check = function (str) {
            var results = ipMatch.exec(str);
            if (results) {
                return results[0];
            }
        };
        var ip = check(this.rawHeaders["x-forwarded-for"])
            || check(this.rawHeaders["x-client-ip"])
            || check(this.rawHeaders["x-real-ip"])
            || check(this.connectionRemoteAddress)
            || check(this.socketRemoteAddress)
            || check(this.legacySocketRemoteAddress);
        // node v12 returns this if the address is "localhost"
        if (!ip
            && this.connectionRemoteAddress
            && this.connectionRemoteAddress.substr
            && this.connectionRemoteAddress.substr(0, 2) === "::") {
            ip = "127.0.0.1";
        }
        return ip;
    };
    ServerRequestParser.prototype._getId = function (name) {
        var cookie = (this.rawHeaders && this.rawHeaders["cookie"] &&
            typeof this.rawHeaders["cookie"] === 'string' && this.rawHeaders["cookie"]) || "";
        var value = ServerRequestParser.parseId(Util.getCookie(name, cookie));
        return value;
    };
    ServerRequestParser.parseId = function (cookieValue) {
        return cookieValue.substr(0, cookieValue.indexOf('|'));
    };
    ServerRequestParser.keys = new ContractsModule.Contracts.ContextTagKeys();
    return ServerRequestParser;
}(RequestParser));
module.exports = ServerRequestParser;
