"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
var cloud_functions_1 = require("../cloud-functions");
var _ = require("lodash");
/** @internal */
exports.provider = 'google.firebase.analytics';
/**
 * Registers a Cloud Function to handle analytics events.
 *
 * @param {string} analyticsEventType Name of the analytics event type to which
 *   this Cloud Function is scoped.
 *
 * @return {!functions.analytics.AnalyticsEventBuilder} Analytics event builder
 *   interface.
 */
function event(analyticsEventType) {
    return new AnalyticsEventBuilder('projects/' + process.env.GCLOUD_PROJECT + '/events/' + analyticsEventType);
}
exports.event = event;
/**
 * The Firebase Analytics event builder interface.
 *
 * Access via [`functions.analytics.event()`](functions.analytics#event).
 */
var AnalyticsEventBuilder = (function () {
    /** @internal */
    function AnalyticsEventBuilder(resource) {
        this.resource = resource;
    }
    /**
     * Event handler that fires every time a Firebase Analytics event occurs.
     *
     * @param {!function(!functions.Event<!functions.analytics.AnalyticsEvent>)}
     *   handler Event handler that fires every time a Firebase Analytics event
     *   occurs.
     *
     * @return {!functions.CloudFunction<!functions.analytics.AnalyticsEvent>} A
     *   Cloud Function you can export.
     */
    AnalyticsEventBuilder.prototype.onLog = function (handler) {
        var dataConstructor = function (raw) {
            return new AnalyticsEvent(raw.data);
        };
        return cloud_functions_1.makeCloudFunction({
            provider: exports.provider,
            handler: handler,
            eventType: 'event.log',
            resource: this.resource,
            dataConstructor: dataConstructor,
        });
    };
    return AnalyticsEventBuilder;
}());
exports.AnalyticsEventBuilder = AnalyticsEventBuilder;
/**
 * Interface representing a Firebase Analytics event that was logged for a specific user.
 */
var AnalyticsEvent = (function () {
    /** @internal */
    function AnalyticsEvent(wireFormat) {
        this.params = {}; // In case of absent field, show empty (not absent) map.
        if (wireFormat.eventDim && wireFormat.eventDim.length > 0) {
            // If there's an eventDim, there'll always be exactly one.
            var eventDim = wireFormat.eventDim[0];
            copyField(eventDim, this, 'name');
            copyField(eventDim, this, 'params', function (p) { return _.mapValues(p, unwrapValue); });
            copyFieldTo(eventDim, this, 'valueInUsd', 'valueInUSD');
            copyFieldTo(eventDim, this, 'date', 'reportingDate');
            copyTimestampToString(eventDim, this, 'timestampMicros', 'logTime');
            copyTimestampToString(eventDim, this, 'previousTimestampMicros', 'previousLogTime');
        }
        copyFieldTo(wireFormat, this, 'userDim', 'user', function (dim) { return new UserDimensions(dim); });
    }
    return AnalyticsEvent;
}());
exports.AnalyticsEvent = AnalyticsEvent;
/**
 * Interface representing the user who triggered the events.
 */
var UserDimensions = (function () {
    /** @internal */
    function UserDimensions(wireFormat) {
        // These are interfaces or primitives, no transformation needed.
        copyFields(wireFormat, this, ['userId', 'deviceInfo', 'geoInfo', 'appInfo']);
        // The following fields do need transformations of some sort.
        copyTimestampToString(wireFormat, this, 'firstOpenTimestampMicros', 'firstOpenTime');
        this.userProperties = {}; // With no entries in the wire format, present an empty (as opposed to absent) map.
        copyField(wireFormat, this, 'userProperties', function (r) { return _.mapValues(r, function (p) { return new UserPropertyValue(p); }); });
        copyField(wireFormat, this, 'bundleInfo', function (r) { return new ExportBundleInfo(r); });
        // BUG(36000368) Remove when no longer necessary
        /* tslint:disable:no-string-literal */
        if (!this.userId && this.userProperties['user_id']) {
            this.userId = this.userProperties['user_id'].value;
        }
        /* tslint:enable:no-string-literal */
    }
    return UserDimensions;
}());
exports.UserDimensions = UserDimensions;
/**
 * Predefined or custom properties stored on the client side.
 */
var UserPropertyValue = (function () {
    /** @internal */
    function UserPropertyValue(wireFormat) {
        copyField(wireFormat, this, 'value', unwrapValueAsString);
        copyTimestampToString(wireFormat, this, 'setTimestampUsec', 'setTime');
    }
    return UserPropertyValue;
}());
exports.UserPropertyValue = UserPropertyValue;
/**
 * Interface representing the bundle in which these events were uploaded.
 */
var ExportBundleInfo = (function () {
    /** @internal */
    function ExportBundleInfo(wireFormat) {
        copyField(wireFormat, this, 'bundleSequenceId');
        copyTimestampToMillis(wireFormat, this, 'serverTimestampOffsetMicros', 'serverTimestampOffset');
    }
    return ExportBundleInfo;
}());
exports.ExportBundleInfo = ExportBundleInfo;
function copyFieldTo(from, to, fromField, toField, transform) {
    if (transform === void 0) { transform = _.identity; }
    if (from[fromField] !== undefined) {
        to[toField] = transform(from[fromField]);
    }
}
function copyField(from, to, field, transform) {
    if (transform === void 0) { transform = _.identity; }
    copyFieldTo(from, to, field, field, transform);
}
function copyFields(from, to, fields) {
    for (var _i = 0, fields_1 = fields; _i < fields_1.length; _i++) {
        var field = fields_1[_i];
        copyField(from, to, field);
    }
}
// The incoming payload will have fields like:
// {
//   'myInt': {
//     'intValue': '123'
//   },
//   'myDouble': {
//     'doubleValue': 1.0
//   },
//   'myFloat': {
//     'floatValue': 1.1
//   },
//   'myString': {
//     'stringValue': 'hi!'
//   }
// }
//
// The following method will remove these four types of 'xValue' fields, flattening them
// to just their values, as a string:
// {
//   'myInt': '123',
//   'myDouble': '1.0',
//   'myFloat': '1.1',
//   'myString': 'hi!'
// }
//
// Note that while 'intValue' will have a quoted payload, 'doubleValue' and 'floatValue' will not. This
// is due to the encoding library, which renders int64 values as strings to avoid loss of precision. This
// method always returns a string, similarly to avoid loss of precision, unlike the less-conservative
// 'unwrapValue' method just below.
function unwrapValueAsString(wrapped) {
    var key = _.keys(wrapped)[0];
    return _.toString(wrapped[key]);
}
// Ditto as the method above, but returning the values in the idiomatic JavaScript type (string for strings,
// number for numbers):
// {
//   'myInt': 123,
//   'myDouble': 1.0,
//   'myFloat': 1.1,
//   'myString': 'hi!'
// }
//
// The field names in the incoming xValue fields identify the type a value has, which for JavaScript's
// purposes can be divided into 'number' versus 'string'. This method will render all the numbers as
// JavaScript's 'number' type, since we prefer using idiomatic types. Note that this may lead to loss
// in precision for int64 fields, so use with care.
var xValueNumberFields = ['intValue', 'floatValue', 'doubleValue'];
function unwrapValue(wrapped) {
    var key = _.keys(wrapped)[0];
    var value = unwrapValueAsString(wrapped);
    return _.includes(xValueNumberFields, key) ? _.toNumber(value) : value;
}
// The JSON payload delivers timestamp fields as strings of timestamps denoted in microseconds.
// The JavaScript convention is to use numbers denoted in milliseconds. This method
// makes it easy to convert a field of one type into the other.
function copyTimestampToMillis(from, to, fromName, toName) {
    if (from[fromName] !== undefined) {
        to[toName] = _.round(from[fromName] / 1000);
    }
}
// The JSON payload delivers timestamp fields as strings of timestamps denoted in microseconds.
// In our SDK, we'd like to present timestamp as ISO-format strings. This method makes it easy
// to convert a field of one type into the other.
function copyTimestampToString(from, to, fromName, toName) {
    if (from[fromName] !== undefined) {
        to[toName] = (new Date(from[fromName] / 1000)).toISOString();
    }
}
