"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleHover = handleHover;
const dom_util_1 = require("@mablhq-internal/mablscript-find/dom-util");
const domUtils_1 = require("../../sharedUtils/domUtils");
const actionTypes_1 = require("../../sharedUtils/actionTypes");
const stateUtils_1 = require("../stateUtils");
const BaseContentEventHandler_1 = require("./BaseContentEventHandler");
const util_1 = require("./util");
const domTools_1 = require("../domTools");
const walkthrough_1 = require("../../sharedUtils/walkthrough");
const actions_1 = require("../actions");
class MouseHoverEventHandler extends BaseContentEventHandler_1.BaseContentEventHandler {
    constructor(store, selectorCache) {
        super('mouseover', 'Mouse Hover Event Handler', store, selectorCache);
        this.handle = this.handle.bind(this);
        this.recordHovers = this.recordHovers.bind(this);
    }
    handle(event) {
        const state = this.store.getState();
        if (!(0, stateUtils_1.isCapturingHovers)(state) ||
            !(0, util_1.shouldListenForTrainedStepInRecording)(state) ||
            !(0, util_1.isTrustedEvent)(event)) {
            return;
        }
        const { path, target } = (0, domUtils_1.adjustTarget)(event.target, (0, util_1.getPathOnEvent)(event));
        if (!target) {
            return;
        }
        const isInWalkthrough = this.store.getState().walkthrough.isInProgress;
        if (isInWalkthrough) {
            const isInTrainerContext = this.store.getState().walkthrough.activeContext ===
                walkthrough_1.ActiveWalkthroughContext.TRAINER;
            if (isInTrainerContext || !(0, util_1.isWalkthroughTarget)(target)) {
                return;
            }
        }
        const xPath = (0, dom_util_1.createXpathFromPathArray)(path);
        handleHover(event, xPath, this.store.dispatch, state);
    }
    recordHovers() {
        const state = this.store.getState();
        if ((0, stateUtils_1.isCapturingHovers)(state) &&
            (0, util_1.shouldListenForTrainedStepInRecording)(state)) {
            this.store.dispatch((0, actionTypes_1.recordHovers)());
        }
    }
}
exports.default = MouseHoverEventHandler;
function handleHover(event, xPath, dispatch, state) {
    (0, actions_1.sendSnapshotMessage)();
    const previousHoverIndex = state.hover.hoverXpathToIndex[xPath];
    if (previousHoverIndex === undefined) {
        const eventMessage = (0, domTools_1.createBaseEventMessageWithShadowParents)(event, 'record', 'hover', xPath, event.timeStamp);
        dispatch(receiveHover(eventMessage));
    }
    else {
        dispatch(removeHover(previousHoverIndex));
    }
}
function receiveHover(eventMessage) {
    return {
        type: actionTypes_1.RECEIVE_HOVER,
        eventMessage,
    };
}
function removeHover(hoverIndex) {
    return {
        type: actionTypes_1.REMOVE_HOVER,
        hoverIndex,
    };
}
