"use strict";
/**
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TraceModel = exports.trace = void 0;
const utils_1 = require("../../../utils/utils");
const frameSnapshot_1 = require("./frameSnapshot");
exports.trace = __importStar(require("../common/traceEvents"));
class TraceModel {
    constructor() {
        this.contextEntries = new Map();
        this.pageEntries = new Map();
        this.resourceById = new Map();
    }
    appendEvents(events) {
        for (const event of events)
            this.appendEvent(event);
    }
    appendEvent(event) {
        var _a;
        switch (event.type) {
            case 'context-created': {
                this.contextEntries.set(event.contextId, {
                    name: event.debugName || utils_1.createGuid(),
                    startTime: Number.MAX_VALUE,
                    endTime: Number.MIN_VALUE,
                    created: event,
                    destroyed: undefined,
                    pages: [],
                    resourcesByUrl: {},
                    overriddenUrls: {}
                });
                break;
            }
            case 'context-destroyed': {
                this.contextEntries.get(event.contextId).destroyed = event;
                break;
            }
            case 'page-created': {
                const pageEntry = {
                    created: event,
                    destroyed: undefined,
                    actions: [],
                    resources: [],
                    interestingEvents: [],
                    snapshotsByFrameId: {},
                };
                const contextEntry = this.contextEntries.get(event.contextId);
                this.pageEntries.set(event.pageId, { pageEntry, contextEntry });
                contextEntry.pages.push(pageEntry);
                break;
            }
            case 'page-destroyed': {
                this.pageEntries.get(event.pageId).pageEntry.destroyed = event;
                break;
            }
            case 'action': {
                if (!kInterestingActions.includes(event.method))
                    break;
                const { pageEntry } = this.pageEntries.get(event.pageId);
                const actionId = event.contextId + '/' + event.pageId + '/' + pageEntry.actions.length;
                const action = {
                    actionId,
                    action: event,
                    thumbnailUrl: `/action-preview/${actionId}.png`,
                    resources: pageEntry.resources,
                };
                pageEntry.resources = [];
                pageEntry.actions.push(action);
                break;
            }
            case 'resource': {
                const { pageEntry } = this.pageEntries.get(event.pageId);
                const action = pageEntry.actions[pageEntry.actions.length - 1];
                (action || pageEntry).resources.push(event);
                this.appendResource(event);
                break;
            }
            case 'dialog-opened':
            case 'dialog-closed':
            case 'navigation':
            case 'load': {
                const { pageEntry } = this.pageEntries.get(event.pageId);
                pageEntry.interestingEvents.push(event);
                break;
            }
            case 'snapshot': {
                const { pageEntry } = this.pageEntries.get(event.pageId);
                let snapshots = pageEntry.snapshotsByFrameId[event.frameId];
                if (!snapshots) {
                    snapshots = [];
                    pageEntry.snapshotsByFrameId[event.frameId] = snapshots;
                }
                snapshots.push(event);
                const contextEntry = this.contextEntries.get(event.contextId);
                for (const override of event.snapshot.resourceOverrides) {
                    if (override.ref) {
                        const refOverride = (_a = snapshots[snapshots.length - 1 - override.ref]) === null || _a === void 0 ? void 0 : _a.snapshot.resourceOverrides.find(o => o.url === override.url);
                        override.sha1 = refOverride === null || refOverride === void 0 ? void 0 : refOverride.sha1;
                        delete override.ref;
                    }
                    contextEntry.overriddenUrls[override.url] = true;
                }
                break;
            }
        }
        const contextEntry = this.contextEntries.get(event.contextId);
        contextEntry.startTime = Math.min(contextEntry.startTime, event.timestamp);
        contextEntry.endTime = Math.max(contextEntry.endTime, event.timestamp);
    }
    appendResource(event) {
        const contextEntry = this.contextEntries.get(event.contextId);
        let responseEvents = contextEntry.resourcesByUrl[event.url];
        if (!responseEvents) {
            responseEvents = [];
            contextEntry.resourcesByUrl[event.url] = responseEvents;
        }
        responseEvents.push({ frameId: event.frameId, resourceId: event.resourceId });
        this.resourceById.set(event.resourceId, event);
    }
    actionById(actionId) {
        const [contextId, pageId, actionIndex] = actionId.split('/');
        const context = this.contextEntries.get(contextId);
        const page = context.pages.find(entry => entry.created.pageId === pageId);
        const action = page.actions[+actionIndex];
        return { context, page, action };
    }
    findPage(pageId) {
        let contextEntry;
        let pageEntry;
        for (const c of this.contextEntries.values()) {
            for (const p of c.pages) {
                if (p.created.pageId === pageId) {
                    contextEntry = c;
                    pageEntry = p;
                }
            }
        }
        return { contextEntry, pageEntry };
    }
    findSnapshotById(pageId, frameId, snapshotId) {
        const { pageEntry, contextEntry } = this.pageEntries.get(pageId);
        const frameSnapshots = pageEntry.snapshotsByFrameId[frameId];
        for (let index = 0; index < frameSnapshots.length; index++) {
            if (frameSnapshots[index].snapshotId === snapshotId)
                return new frameSnapshot_1.FrameSnapshot(contextEntry, frameSnapshots, index);
        }
    }
    findSnapshotByTime(pageId, frameId, timestamp) {
        const { pageEntry, contextEntry } = this.pageEntries.get(pageId);
        const frameSnapshots = pageEntry.snapshotsByFrameId[frameId];
        let snapshotIndex = -1;
        for (let index = 0; index < frameSnapshots.length; index++) {
            const snapshot = frameSnapshots[index];
            if (timestamp && snapshot.timestamp <= timestamp)
                snapshotIndex = index;
        }
        return snapshotIndex >= 0 ? new frameSnapshot_1.FrameSnapshot(contextEntry, frameSnapshots, snapshotIndex) : undefined;
    }
}
exports.TraceModel = TraceModel;
const kInterestingActions = ['click', 'dblclick', 'hover', 'check', 'uncheck', 'tap', 'fill', 'press', 'type', 'selectOption', 'setInputFiles', 'goto', 'setContent', 'goBack', 'goForward', 'reload'];
//# sourceMappingURL=traceModel.js.map