"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
require("@testing-library/jest-dom");
require("@testing-library/jest-dom/extend-expect");
const react_2 = require("@testing-library/react");
const types_1 = require("../types");
const test_utils_1 = require("../test/test-utils");
const index_1 = require("./index");
const allExports = tslib_1.__importStar(require("./index"));
const index_2 = require("../index");
const package_json_1 = require("../../package.json");
const auth = tslib_1.__importStar(require("../auth"));
const sessionService = tslib_1.__importStar(require("../utils/sessionInfoService"));
const thoughtSpotHost = 'localhost';
beforeAll(() => {
    (0, index_2.init)({
        thoughtSpotHost,
        authType: index_2.AuthType.None,
    });
    jest.spyOn(auth, 'postLoginService').mockReturnValue(true);
    jest.spyOn(sessionService, 'getSessionInfo').mockReturnValue({
        userGUID: 'abcd',
    });
    spyOn(window, 'alert');
});
describe('React Components', () => {
    describe('SearchEmbed', () => {
        it('Should Render the Iframe with props', async () => {
            const { container } = (0, react_2.render)(react_1.default.createElement(index_1.SearchEmbed, { hideDataSources: true, className: "embedClass" }));
            await (0, react_2.waitFor)(() => (0, test_utils_1.getIFrameEl)(container));
            expect((0, test_utils_1.getIFrameEl)(container).parentElement.classList.contains('embedClass')).toBe(true);
            expect((0, test_utils_1.getIFrameSrc)(container)).toBe(`http://${thoughtSpotHost}/?embedApp=true&hostAppUrl=local-host&viewPortHeight=768&viewPortWidth=1024&sdkVersion=${package_json_1.version}&authType=None&blockNonEmbedFullAppAccess=true&hideAction=[%22${types_1.Action.ReportError}%22,%22editACopy%22,%22saveAsView%22,%22updateTSL%22,%22editTSL%22,%22onDeleteAnswer%22]&preAuthCache=true&overrideConsoleLogs=true&clientLogLevel=ERROR&enableDataPanelV2=false&dataSourceMode=hide&useLastSelectedSources=false&isSearchEmbed=true&collapseSearchBarInitially=true&enableCustomColumnGroups=false&dataPanelCustomGroupsAccordionInitialState=EXPAND_ALL#/embed/answer`);
        });
        it('Should attach event listeners', async (done) => {
            const userGUID = 'absfdfgd';
            const { container } = (0, react_2.render)(react_1.default.createElement(index_1.SearchEmbed, { onInit: (e) => {
                    expect(e.data).toHaveProperty('timestamp');
                }, onAuthInit: (e) => {
                    expect(e.data.userGUID).toEqual(userGUID);
                    done();
                } }));
            await (0, react_2.waitFor)(() => (0, test_utils_1.getIFrameEl)(container));
            const iframe = (0, test_utils_1.getIFrameEl)(container);
            (0, test_utils_1.postMessageToParent)(iframe.contentWindow, {
                type: types_1.EmbedEvent.AuthInit,
                data: {
                    userGUID,
                },
            });
        });
    });
    describe('AppEmbed', () => {
        //
    });
    describe('LiveboardEmbed', () => {
        //
        it('Should be able to trigger events on the embed using refs', async () => {
            (0, test_utils_1.mockMessageChannel)();
            const TestComponent = () => {
                const embedRef = (0, index_1.useEmbedRef)();
                const onLiveboardRendered = () => {
                    embedRef.current.trigger(types_1.HostEvent.SetVisibleVizs, ['viz1', 'viz2']);
                };
                return (react_1.default.createElement(index_1.LiveboardEmbed, { ref: embedRef, liveboardId: "abcd", onLiveboardRendered: onLiveboardRendered }));
            };
            const { container } = (0, react_2.render)(react_1.default.createElement(TestComponent, null));
            await (0, react_2.waitFor)(() => (0, test_utils_1.getIFrameEl)(container));
            const iframe = (0, test_utils_1.getIFrameEl)(container);
            jest.spyOn(iframe.contentWindow, 'postMessage');
            (0, test_utils_1.postMessageToParent)(iframe.contentWindow, {
                type: types_1.EmbedEvent.LiveboardRendered,
                data: {
                    userGUID: 'abcd',
                },
            });
            await (0, test_utils_1.executeAfterWait)(() => {
                expect(iframe.contentWindow.postMessage).toHaveBeenCalledWith({
                    type: types_1.HostEvent.SetVisibleVizs,
                    data: ['viz1', 'viz2'],
                }, `http://${thoughtSpotHost}`, expect.anything());
            });
        });
        it('Should render liveboard with runtime filters', async () => {
            const { container } = (0, react_2.render)(react_1.default.createElement(index_1.LiveboardEmbed, { liveboardId: "abcd", runtimeFilters: [
                    {
                        columnName: 'revenue',
                        operator: types_1.RuntimeFilterOp.EQ,
                        values: [100],
                    },
                ], excludeRuntimeFiltersfromURL: false }));
            await (0, react_2.waitFor)(() => (0, test_utils_1.getIFrameEl)(container));
            expect((0, test_utils_1.getIFrameSrc)(container)).toContain('col1=revenue&op1=EQ&val1=100');
        });
        it('Should have the correct container element', async () => {
            const { container } = (0, react_2.render)(react_1.default.createElement(index_1.LiveboardEmbed, { liveboardId: "abcd", className: "def" }));
            await (0, react_2.waitFor)(() => (0, test_utils_1.getIFrameEl)(container));
            expect(container.querySelector('div')).not.toBe(null);
            expect(container.querySelector('div').classList.contains('def')).toBe(true);
            const { container: containerSibling } = (0, react_2.render)(react_1.default.createElement(index_1.LiveboardEmbed, { liveboardId: "abcd", className: "def", insertAsSibling: true }));
            await (0, react_2.waitFor)(() => (0, test_utils_1.getIFrameEl)(containerSibling));
            expect(containerSibling.querySelector('span')).not.toBe(null);
            expect(containerSibling.querySelector('span').style.position).toBe('absolute');
            expect((0, test_utils_1.getIFrameEl)(containerSibling).classList.contains('def')).toBe(true);
            expect(containerSibling.querySelector('div')).toBe(null);
        });
        it('Should have the correct container element', async () => {
            const { container } = (0, react_2.render)(react_1.default.createElement(index_1.LiveboardEmbed, { liveboardId: "abcd", className: "def" }));
            await (0, react_2.waitFor)(() => (0, test_utils_1.getIFrameEl)(container));
            expect(container.querySelector('div')).not.toBe(null);
            expect(container.querySelector('div').classList.contains('def')).toBe(true);
            const { container: containerSibling } = (0, react_2.render)(react_1.default.createElement(index_1.LiveboardEmbed, { liveboardId: "abcd", className: "def", insertAsSibling: true }));
            await (0, react_2.waitFor)(() => (0, test_utils_1.getIFrameEl)(containerSibling));
            expect(containerSibling.querySelector('span')).not.toBe(null);
            expect(containerSibling.querySelector('span').style.position).toBe('absolute');
            expect((0, test_utils_1.getIFrameEl)(containerSibling).classList.contains('def')).toBe(true);
            expect(containerSibling.querySelector('div')).toBe(null);
        });
    });
    describe('SearchBarEmbed', () => {
        it('Should Render the Iframe with props', async () => {
            const { container } = (0, react_2.render)(react_1.default.createElement(index_1.SearchBarEmbed, { className: "embedClass", dataSource: 'test', searchOptions: {
                    searchTokenString: '[revenue]',
                    executeSearch: true,
                } }));
            await (0, react_2.waitFor)(() => (0, test_utils_1.getIFrameEl)(container));
            expect((0, test_utils_1.getIFrameEl)(container).parentElement.classList.contains('embedClass')).toBe(true);
            expect((0, test_utils_1.getIFrameSrc)(container)).toBe(`http://${thoughtSpotHost}/?embedApp=true&hostAppUrl=local-host&viewPortHeight=768&viewPortWidth=1024&sdkVersion=${package_json_1.version}&authType=None&blockNonEmbedFullAppAccess=true&hideAction=[%22${types_1.Action.ReportError}%22]&preAuthCache=true&overrideConsoleLogs=true&clientLogLevel=ERROR&dataSources=[%22test%22]&searchTokenString=%5Brevenue%5D&executeSearch=true&useLastSelectedSources=false&isSearchEmbed=true#/embed/search-bar-embed`);
        });
    });
    describe('SpotterAgentEmbed', () => {
        it('Should work as a React component integrating BodylessConversation', async () => {
            const mockDiv = document.createElement('div');
            let conversationService = null;
            (0, react_2.render)(react_1.default.createElement(index_1.SpotterAgentEmbed, { ref: (instance) => {
                    conversationService = instance;
                    if (instance) {
                        instance.sendMessage = jest.fn().mockResolvedValue({
                            container: mockDiv
                        });
                    }
                }, worksheetId: "test-worksheet-id" }));
            expect(conversationService).not.toBeNull();
            if (conversationService) {
                expect(typeof conversationService.sendMessage).toBe('function');
                const response = await conversationService.sendMessage("What are my sales this month?");
                expect(response.container).toBe(mockDiv);
            }
        });
        it('Should work as a React component with ref support', () => {
            const mockSendMessage = jest.fn().mockResolvedValue({
                container: document.createElement('div'),
                viz: {}
            });
            const TestComponent = () => {
                const conversationRef = react_1.default.useRef(null);
                const handleClick = () => {
                    if (conversationRef.current) {
                        conversationRef.current.sendMessage = mockSendMessage;
                        conversationRef.current.sendMessage("Test message");
                    }
                };
                return (react_1.default.createElement(react_1.default.Fragment, null,
                    react_1.default.createElement(index_1.SpotterAgentEmbed, { ref: conversationRef, worksheetId: "test-worksheet-id" }),
                    react_1.default.createElement("button", { "data-testid": "test-button", onClick: handleClick }, "Send Message")));
            };
            const { getByTestId } = (0, react_2.render)(react_1.default.createElement(TestComponent, null));
            react_2.fireEvent.click(getByTestId('test-button'));
            expect(mockSendMessage).toHaveBeenCalledWith("Test message");
        });
        it('Should work with the useEmbedRef hook', () => {
            const mockSendMessage = jest.fn().mockResolvedValue({
                container: document.createElement('div'),
                viz: {}
            });
            const TestComponent = () => {
                const embedRef = (0, index_1.useEmbedRef)();
                const handleClick = () => {
                    if (embedRef.current) {
                        const service = embedRef.current;
                        service.sendMessage = mockSendMessage;
                        service.sendMessage("Test with useEmbedRef");
                    }
                };
                return (react_1.default.createElement(react_1.default.Fragment, null,
                    react_1.default.createElement(index_1.SpotterAgentEmbed, { ref: embedRef, worksheetId: "test-worksheet-id" }),
                    react_1.default.createElement("button", { "data-testid": "use-embed-ref-button", onClick: handleClick }, "Send with useEmbedRef")));
            };
            const { getByTestId } = (0, react_2.render)(react_1.default.createElement(TestComponent, null));
            react_2.fireEvent.click(getByTestId('use-embed-ref-button'));
            expect(mockSendMessage).toHaveBeenCalledWith("Test with useEmbedRef");
        });
        it('Should work with the className prop', async () => {
            let capturedInstance = null;
            const TestComponent = () => {
                const embedRef = (0, index_1.useEmbedRef)();
                react_1.default.useEffect(() => {
                    capturedInstance = embedRef.current;
                    if (capturedInstance) {
                        const mockConversationService = {
                            sendMessage: jest.fn().mockResolvedValue({
                                data: {
                                    sessionId: 'test-session',
                                    genNo: 1,
                                    stateKey: {
                                        transactionId: 'test-transaction',
                                        generationNumber: 1
                                    }
                                }
                            })
                        };
                        capturedInstance.conversationService = mockConversationService;
                    }
                }, []);
                return (react_1.default.createElement(index_1.SpotterAgentEmbed, { ref: embedRef, worksheetId: "test-worksheet-id", className: "embedClass" }));
            };
            (0, react_2.render)(react_1.default.createElement(TestComponent, null));
            expect(capturedInstance).not.toBeNull();
            if (capturedInstance) {
                const result = await capturedInstance.sendMessage("test");
                expect(result.container.className).toBe("embedClass");
            }
        });
    });
    describe('PreRenderedLiveboardEmbed', () => {
        it('should preRender the liveboard ', async () => {
            const preRenderId = 'tsEmbed-pre-render-wrapper-test';
            const { container } = (0, react_2.render)(react_1.default.createElement(index_1.PreRenderedLiveboardEmbed, { className: "embedClass", preRenderId: "test", liveboardId: "libId" }));
            await (0, react_2.waitFor)(() => (0, test_utils_1.getIFrameEl)());
            const preRenderWrapper = document.body.querySelector(`#${preRenderId}`);
            expect(preRenderWrapper).toBeInstanceOf(HTMLDivElement);
            expect(preRenderWrapper.childElementCount).toBe(1);
            const preRenderChildId = 'tsEmbed-pre-render-child-test';
            const preRenderChild = document.body.querySelector(`#${preRenderChildId}`);
            expect(preRenderWrapper.children[0]).toBe(preRenderChild);
            window.ResizeObserver = jest.fn().mockImplementation(() => ({
                disconnect: jest.fn(),
                observe: jest.fn(),
                unobserve: jest.fn(),
            }));
            const { container: libContainer } = (0, react_2.render)(react_1.default.createElement(index_1.LiveboardEmbed, { className: "embedClass", preRenderId: "test", liveboardId: "libId" }));
            expect(preRenderWrapper.style.opacity).toBe('');
            expect(preRenderWrapper.style.pointerEvents).toBe('');
            expect(preRenderWrapper.style.zIndex).toBe('');
        });
    });
});
describe('allExports', () => {
    it('should have exports', () => {
        expect(typeof allExports).toBe('object');
    });
    it('should not have undefined exports', () => {
        Object.keys(allExports).forEach((exportKey) => expect(Boolean(allExports[exportKey]))
            .toBe(true));
    });
});
//# sourceMappingURL=index.spec.js.map