"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UniversalAnalytics = void 0;
const dayjs_1 = __importDefault(require("dayjs"));
const Analytics_1 = require("./Analytics");
const DATALAYER_DATE_FORMAT = 'YYYY-M-D';
class UniversalAnalytics extends Analytics_1.Analytics {
    getProductInfo(room, rate, listPosition, quantity) {
        var _a, _b, _c;
        const providerId = (_a = this.hotel) === null || _a === void 0 ? void 0 : _a.providerHotelID;
        const price = rate ? rate.getAveragePrice() : room.getLowestPrice();
        const nameParts = [room.name];
        const idParts = [providerId, room.code];
        if (rate) {
            nameParts.push(rate.name);
            idParts.push(rate.code);
        }
        const product = {
            name: nameParts.join(' - '),
            id: idParts.join(' - '),
            price: price,
            brand: [(_b = this.hotel) === null || _b === void 0 ? void 0 : _b.name, providerId, (_c = this.company) === null || _c === void 0 ? void 0 : _c.brandSuffix].filter(Boolean).join(' - '),
            category: room.name,
            category2: 'Rooms',
        };
        if (rate) {
            product.variant = rate.name;
        }
        if (listPosition !== undefined) {
            product.list = this.itemListName;
            product.position = listPosition;
        }
        if (quantity !== undefined) {
            product.quantity = quantity;
        }
        return product;
    }
    generateAddonProductInfo(addonRow, addonRowTotal) {
        var _a, _b, _c;
        const addon = addonRow.getAddon();
        // Uses addon row total from reservations when available, otherwise falls back to addonRow.getTotalPrice().
        const price = addonRowTotal !== null && addonRowTotal !== void 0 ? addonRowTotal : addonRow.getTotalPrice();
        return {
            name: addon.name,
            id: addon.code,
            price: price,
            brand: [(_a = this.hotel) === null || _a === void 0 ? void 0 : _a.name, (_b = this.hotel) === null || _b === void 0 ? void 0 : _b.providerHotelID, (_c = this.company) === null || _c === void 0 ? void 0 : _c.brandSuffix].filter(Boolean).join(' - '),
            category: addon.category,
            category2: 'Addons',
            quantity: addonRow.getTotalQuantity(),
        };
    }
    generateRoomImpressionMessageObject(impressions) {
        return {
            event: 'Product impressions',
            ecommerce: {
                currencyCode: this.currency.original,
                impressions: impressions.map((item, index) => {
                    const { room, quantity } = item;
                    return this.getProductInfo(room, undefined, index, quantity);
                }),
            },
        };
    }
    generateProductClickMessageObject(product) {
        const { room, rate, quantity } = product;
        return {
            event: 'productClick',
            ecommerce: {
                currencyCode: this.currency.original,
                click: {
                    products: [this.getProductInfo(room, rate, undefined, quantity)],
                },
                StartDate: product.dateRange.from.format(DATALAYER_DATE_FORMAT),
                EndDate: product.dateRange.to.format(DATALAYER_DATE_FORMAT),
            },
        };
    }
    generateDateSelectionMessageObject(dateRange, adults, children, infants) {
        return {
            event: 'dateSelection',
            arrivalDate: dateRange.from.format(DATALAYER_DATE_FORMAT),
            departureDate: dateRange.to.format(DATALAYER_DATE_FORMAT),
            adultQty: Number.isInteger(adults) ? `${adults}` : null,
            childQty: Number.isInteger(children) ? `${children}` : null,
            infantQty: Number.isInteger(infants) ? `${infants}` : null,
        };
    }
    generateAddToCartMessageObject(product) {
        const productInfo = this.getProductInfo(product.room, product.rate, undefined, product.quantity);
        return {
            event: 'addToCart',
            ecommerce: {
                currencyCode: this.currency.original,
                add: {
                    products: [productInfo],
                },
                StartDate: product.dateRange.from.format(DATALAYER_DATE_FORMAT),
                EndDate: product.dateRange.to.format(DATALAYER_DATE_FORMAT),
            },
        };
    }
    generateAddonsAddToCartMessageObject(product) {
        return {
            event: 'addToCart',
            ecommerce: {
                currencyCode: this.currency.original,
                add: {
                    products: [this.generateAddonProductInfo(product.basketAddonRow)],
                },
                StartDate: product.dateRange.from.format(DATALAYER_DATE_FORMAT),
                EndDate: product.dateRange.to.format(DATALAYER_DATE_FORMAT),
            },
        };
    }
    generateUpsellConfirmedMessageObject(oldProduct, newProduct) {
        const newRate = newProduct.rate;
        const oldRate = oldProduct.rate;
        if (!newRate || !oldRate) {
            return null;
        }
        const oldConvertedProduct = this.getProductInfo(oldRate.getRoom(), oldRate);
        const newConvertedProduct = this.getProductInfo(newRate.getRoom(), newRate);
        return {
            event: 'upsellConfirmed',
            priceDifference: newRate.getTotalPrice() - oldRate.getTotalPrice(),
            old: {
                products: [oldConvertedProduct],
            },
            new: {
                products: [newConvertedProduct],
            },
        };
    }
    generateUpsellCancelledMessageObject(product) {
        const { room, rate, quantity } = product;
        const productInfo = this.getProductInfo(room, rate, undefined, quantity);
        return {
            event: 'upsellCancelled',
            item: [productInfo],
        };
    }
    generateCheckoutViewMessageObject(basketRows, addonRows) {
        const products = [];
        let startDate = undefined;
        let endDate = undefined;
        basketRows.forEach((row) => {
            startDate = row.getStartDate();
            endDate = row.getEndDate();
            products.push(this.getProductInfo(row.getRoom(), row.getRate(), undefined, row.getNumberOfDays()));
        });
        addonRows.forEach((row) => {
            products.push(this.generateAddonProductInfo(row));
        });
        return {
            event: 'checkout',
            ecommerce: {
                currencyCode: this.currency.original,
                checkout: {
                    actionField: { step: 1 },
                    products,
                },
                StartDate: startDate === null || startDate === void 0 ? void 0 : startDate.format(DATALAYER_DATE_FORMAT),
                EndDate: endDate === null || endDate === void 0 ? void 0 : endDate.format(DATALAYER_DATE_FORMAT),
                PageType: 'conversionintent',
            },
        };
    }
    generateRoomPurchaseMessageObject(basketRows, addonRows, reservations) {
        let i = 0;
        return basketRows
            .map((row) => {
            var _a;
            const products = [this.getProductInfo(row.getRoom(), row.getRate(), undefined, row.getNumberOfDays())];
            if (i === 0) {
                addonRows.forEach((addonRow) => {
                    const addonRowTotal = this.getAddonRowTotalFromReservations(addonRow, reservations);
                    products.push(this.generateAddonProductInfo(addonRow, addonRowTotal));
                });
            }
            try {
                const upsellPrevRoom = row.getPreUpsellRoomRate();
                const extraData = {};
                if (upsellPrevRoom) {
                    extraData.checkoutUpsell = {
                        active: true,
                        oldRoom: upsellPrevRoom.getRoom().code,
                        newRoom: row.getRoom().code,
                        priceDifference: (((_a = row.getRate()) === null || _a === void 0 ? void 0 : _a.getTotalPrice()) || 0) - (upsellPrevRoom.getTotalPrice() || 0),
                    };
                }
                return {
                    event: 'roomPurchase',
                    ecommerce: Object.assign({ currencyCode: this.currency.original, purchase: {
                            actionField: {
                                id: reservations.reservations[i].reservationNumber,
                                revenue: reservations.reservations[i].total.afterTax,
                                tax: reservations.reservations[i].total.afterTax - reservations.reservations[i].total.beforeTax,
                                coupon: row.getPromoCode(),
                            },
                            products,
                        }, StartDate: row.getStartDate().format(DATALAYER_DATE_FORMAT), EndDate: row.getEndDate().format(DATALAYER_DATE_FORMAT), BookingDate: (0, dayjs_1.default)().format(DATALAYER_DATE_FORMAT), PageType: 'conversion', paymentType: reservations.reservations[i].paymentMethod }, extraData),
                };
            }
            catch (e) {
                return undefined;
            }
            finally {
                i++;
            }
        })
            .filter((tmp) => tmp !== undefined);
    }
    generateRefundMessageObject(reservation) {
        return {
            event: 'refund',
            ecommerce: {
                refund: {
                    actionField: {
                        id: reservation.reservationNumber,
                    },
                },
            },
        };
    }
}
const ua = new UniversalAnalytics();
exports.UniversalAnalytics = ua;
//# sourceMappingURL=UniversalAnalytics.js.map