"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a, _b;
Object.defineProperty(exports, "__esModule", { value: true });
const test_1 = require("@playwright/test");
const set_1 = __importDefault(require("lodash/set"));
const args = process.argv.slice(3);
// Extracting CLI parameters
const version = args[0] || process.env.PLAYWRIGHT_VERSION;
const hotelId = args[1] || process.env.PLAYWRIGHT_HOTEL_ID;
const startDate = args[2] || process.env.PLAYWRIGHT_START_DATE;
const endDate = args[3] || process.env.PLAYWRIGHT_END_DATE;
const children = parseInt(args[4], 10) || parseInt(process.env.PLAYWRIGHT_CHILDREN || '0', 10);
const adults = parseInt(args[5], 10) || parseInt(process.env.PLAYWRIGHT_ADULTS || '1', 10);
const promocode = (_b = (_a = args[6]) !== null && _a !== void 0 ? _a : process.env.PLAYWRIGHT_PROMOCODE) !== null && _b !== void 0 ? _b : '';
// Set environment variables with PLAYWRIGHT_ prefix if parameters are provided
if (version) {
    process.env.PLAYWRIGHT_VERSION = version;
}
if (hotelId) {
    process.env.PLAYWRIGHT_HOTEL_ID = hotelId;
}
if (startDate) {
    process.env.PLAYWRIGHT_START_DATE = startDate;
}
if (endDate) {
    process.env.PLAYWRIGHT_END_DATE = endDate;
}
if (!isNaN(children)) {
    process.env.PLAYWRIGHT_CHILDREN = children.toString();
}
if (!isNaN(adults)) {
    process.env.PLAYWRIGHT_ADULTS = adults.toString();
}
if (promocode) {
    process.env.PLAYWRIGHT_PROMOCODE = promocode;
}
if (!version || !hotelId || !startDate || !endDate || isNaN(children) || isNaN(adults)) {
    console.error('Usage: yarn run test:playwright <version> <hotelId> <startDate> <endDate> <children> <adults> <promocode>');
    console.error('Example: yarn run test:playwright 2/6.13 fa737326-ccdb-496a-bd31-2fbc3e97ed59 2024-08-28 2024-08-30 1 2');
    process.exit(1);
}
const url = `https://production.app.roomstay.io/${version}/feature.html?engine=fp&hotel=${hotelId}#/step/date/?arrive=${startDate}&depart=${endDate}&children=${children}&adults=${adults}&promocode=${promocode}`;
const params = { version, hotelId, startDate, endDate, children, adults, promocode, url };
console.log(params);
const spinnerSelector = '[name=Spinner]';
// function waitForAnimationEnd(locator: Locator) {
//     return locator.evaluate((element) => Promise.all(element.getAnimations().map((animation) => animation.finished)));
// }
const getPrice = (text) => {
    const textPrice = text === null || text === void 0 ? void 0 : text.replace(/[a-zA-Z$]/g, '');
    return textPrice && !isNaN(+textPrice) ? +textPrice : undefined;
};
const TIMEOUT = 5 * 60 * 1000;
test_1.test.setTimeout(TIMEOUT);
(0, test_1.test)('price', (_a) => __awaiter(void 0, [_a], void 0, function* ({ page }) {
    var _b;
    //------------------------------------INIT------------------------------------
    yield page.goto(url);
    //------------------------------------WAIT HOTEL APPLIED------------------------------------
    const [hotelResponse] = yield Promise.all([
        page.waitForResponse((resp) => {
            const url = new URL(resp.url()).pathname.replace(/\/$/, '').endsWith(`/frontend/hotel/${hotelId}`);
            return url && resp.status() === 200;
        }),
        page.waitForResponse((resp) => {
            const url = new URL(resp.url()).pathname.replace(/\/$/, '').endsWith(`/frontend/availability/${hotelId}`);
            return url && resp.status() === 200;
        }),
    ]);
    const responseData = yield hotelResponse.json();
    console.log({ responseData });
    yield Promise.all([(0, test_1.expect)(page.locator('.hotel-name')).toHaveText(responseData.name), (0, test_1.expect)(page.locator('.room-details-container').first()).toBeVisible()]);
    //------------------------------------INIT------------------------------------
    const roomList = page.locator('.room-details-container');
    //------------------------------------1. TOTAL RATE PRICE------------------------------------
    let rooms = {};
    for (let room of yield roomList.all()) {
        yield room.locator(spinnerSelector).first().waitFor({
            state: 'detached',
        });
        const roomName = yield room.locator('.room-details--content-title').textContent();
        if (!roomName)
            continue;
        yield room
            .getByRole('button', {
            name: 'View rates now',
        })
            .click();
        const cheapestPrice = getPrice(yield room.locator('.room-details--content-price .headline').first().textContent()) || 0;
        (0, set_1.default)(rooms, [roomName, 'cheapestPrice'], cheapestPrice);
        //------------------------------------1. CHEAPEST PRICE------------------------------------
        const rates = room.locator('.room-info.--default');
        for (let rate of yield rates.all()) {
            yield rate.waitFor({
                state: 'attached',
            });
            const rateName = yield rate.locator('.text-body').first().textContent();
            // console.log(`${roomName}-${rateName}`);
            if (!rateName)
                continue;
            // TODO wait for animation to end
            yield page.waitForTimeout(1000);
            // await waitForAnimationEnd(room.nth(2));
            yield rate
                .getByRole('button', {
                name: 'View price breakdown',
            })
                .click();
            const modal = page
                .locator('[class^=SimpleModal]', {
                hasText: '',
            })
                .first();
            yield modal.waitFor({
                state: 'attached',
            });
            const modalSpinners = modal.locator(spinnerSelector);
            for (let spinner of yield modalSpinners.all()) {
                yield spinner.waitFor({
                    state: 'detached',
                });
            }
            const nightlyPrices = modal.locator('.roomstay-tab-content .u-flex.u-marg-bottom');
            const rateTotal = getPrice(yield modal.locator('.room-details--content-price-protection').textContent());
            (0, set_1.default)(rooms, [roomName, 'rates', rateName, 'total'], rateTotal);
            for (let night of yield nightlyPrices.all()) {
                const nightName = yield night.locator('> *:nth-child(1)').textContent();
                const nightPrice = getPrice(yield ((_b = night.locator('> *:nth-child(2)')) === null || _b === void 0 ? void 0 : _b.textContent()));
                if (!nightName || !nightPrice)
                    continue;
                // set(rooms[roomName].rates![rateName].nights![nightName] = {};
                (0, set_1.default)(rooms, [roomName, 'rates', rateName, 'nights', nightName, 'price'], nightPrice);
            }
            yield modal.locator('[name=Close]').click();
            yield modal.waitFor({
                state: 'detached',
            });
        }
    }
    console.log(JSON.stringify(rooms, null, 2));
}));
//# sourceMappingURL=price.spec.js.map