import { __awaiter, __generator } from "tslib";
import { toFacade } from '../../lib/to-facade';
import standard from './fetch-dispatcher';
import batch from './batched-dispatcher';
import { normalize } from './normalize';
function onAlias(analytics, json) {
    var _a, _b, _c, _d;
    var user = analytics.user();
    json.previousId = (_c = (_b = (_a = json.previousId) !== null && _a !== void 0 ? _a : json.from) !== null && _b !== void 0 ? _b : user.id()) !== null && _c !== void 0 ? _c : user.anonymousId();
    json.userId = (_d = json.userId) !== null && _d !== void 0 ? _d : json.to;
    delete json.from;
    delete json.to;
    return json;
}
export function segmentio(analytics, settings, integrations) {
    var _a, _b, _c;
    var apiHost = (_a = settings === null || settings === void 0 ? void 0 : settings.apiHost) !== null && _a !== void 0 ? _a : 'api.segment.io/v1';
    var remote = "https://" + apiHost;
    var client = ((_b = settings === null || settings === void 0 ? void 0 : settings.deliveryStrategy) === null || _b === void 0 ? void 0 : _b.strategy) === 'batching'
        ? batch(apiHost, (_c = settings === null || settings === void 0 ? void 0 : settings.deliveryStrategy) === null || _c === void 0 ? void 0 : _c.config)
        : standard();
    function send(ctx) {
        return __awaiter(this, void 0, void 0, function () {
            var path, json;
            return __generator(this, function (_a) {
                path = ctx.event.type.charAt(0);
                json = toFacade(ctx.event).json();
                if (ctx.event.type === 'track') {
                    delete json.traits;
                }
                if (ctx.event.type === 'alias') {
                    json = onAlias(analytics, json);
                }
                return [2 /*return*/, client
                        .dispatch(remote + "/" + path, normalize(analytics, json, settings, integrations))
                        .then(function () { return ctx; })];
            });
        });
    }
    return {
        name: 'Segment.io',
        type: 'after',
        version: '0.1.0',
        isLoaded: function () { return true; },
        load: function () { return Promise.resolve(); },
        track: send,
        identify: send,
        page: send,
        alias: send,
        group: send,
    };
}
//# sourceMappingURL=index.js.map