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());
    });
};
import { generateApolloClient } from '@deep-foundation/hasura/client.js';
import { DeepClient, useDeepSubscription } from "../imports/client";
import { assert } from 'chai';
import { render, screen, waitFor } from '@testing-library/react';
import { DeepProvider } from '../imports/client';
import React from "react";
import { ApolloProvider } from '@apollo/client/index.js';
import '@testing-library/jest-dom';
import { useDeep } from '../imports/client';
import { ApolloClientTokenizedProvider } from '@deep-foundation/react-hasura/apollo-client-tokenized-provider';
import { TokenProvider } from '../imports/react-token';
import { LocalStoreProvider } from '@deep-foundation/store/local';
import { QueryStoreProvider } from '@deep-foundation/store/query';
import { CookiesStoreProvider } from '@deep-foundation/store/cookies';
import { CapacitorStoreProvider } from "@deep-foundation/store/capacitor";
function Main({ options }) {
    return React.createElement(ApolloClientTokenizedProvider, { options: options },
        React.createElement("div", null));
}
const graphQlPath = `${process.env.DEEPLINKS_HASURA_PATH}/v1/graphql`;
const ssl = !!+process.env.DEEPLINKS_HASURA_SSL;
const secret = process.env.DEEPLINKS_HASURA_SECRET;
const ws = true;
let apolloClient;
let deepClient;
beforeAll(() => __awaiter(void 0, void 0, void 0, function* () {
    apolloClient = generateApolloClient({
        path: graphQlPath,
        ssl,
        secret,
        ws
    });
    deepClient = new DeepClient({ apolloClient });
}));
describe('client-react', () => {
    describe(`useDeepSubscription`, () => {
        it(`type`, () => __awaiter(void 0, void 0, void 0, function* () {
            yield setup();
            expect(screen.getByText('Loading...')).toBeInTheDocument();
            yield waitFor(() => {
                expect(screen.queryByText('Loading...')).not.toBeInTheDocument();
            });
            expect(screen.queryByText(/^Error:/)).not.toBeInTheDocument();
            yield waitFor(() => {
                const dataLengthText = screen.getByText(/items loaded$/);
                expect(dataLengthText).toBeInTheDocument();
                const dataLength = parseInt(dataLengthText.textContent);
                expect(dataLength).toBeGreaterThan(0);
            }, { timeout: 10000 });
            function setup() {
                return __awaiter(this, void 0, void 0, function* () {
                    const typeTypeLinkId = yield deepClient.id("@deep-foundation/core", "Type");
                    function TestHookComponent() {
                        const { loading, data, error } = useDeepSubscription({
                            type_id: typeTypeLinkId,
                        });
                        if (loading) {
                            return React.createElement("div", null, "Loading...");
                        }
                        if (error) {
                            return React.createElement("div", null,
                                "Error: ",
                                error.message);
                        }
                        return React.createElement("div", null,
                            data.length,
                            " items loaded");
                    }
                    render(React.createElement(ApolloProvider, { client: deepClient.apolloClient },
                        React.createElement(DeepProvider, null,
                            React.createElement(TestHookComponent, null))));
                });
            }
        }));
        it('rerender with loading:true must occur only once', () => __awaiter(void 0, void 0, void 0, function* () {
            let renderCount = 0;
            let loadingCount = 0;
            function TestComponent() {
                const deepSubscriptionResult = useDeepSubscription({
                    id: {
                        _id: ['@deep-foundation/core']
                    }
                });
                renderCount += 1;
                if (deepSubscriptionResult.loading) {
                    loadingCount += 1;
                }
                return null;
            }
            render(React.createElement(ApolloProvider, { client: deepClient.apolloClient },
                React.createElement(DeepProvider, null,
                    React.createElement(TestComponent, null))));
            yield waitFor(() => {
                assert(renderCount > 1, 'TestComponent must be rerendered more than once');
                assert(loadingCount === 1, 'loading:true must occur only once');
            });
        }));
        it('rerender with loading:false must occur only once', () => __awaiter(void 0, void 0, void 0, function* () {
            let renderCount = 0;
            let loadingCount = 0;
            function TestComponent() {
                const deepSubscriptionResult = useDeepSubscription({
                    id: {
                        _id: ['@deep-foundation/core']
                    }
                });
                renderCount += 1;
                if (!deepSubscriptionResult.loading) {
                    loadingCount += 1;
                }
                return null;
            }
            render(React.createElement(ApolloProvider, { client: deepClient.apolloClient },
                React.createElement(DeepProvider, null,
                    React.createElement(TestComponent, null))));
            yield waitFor(() => {
                assert(renderCount > 1, 'TestComponent must be rerendered more than once');
                assert(loadingCount === 1, 'loading:false must occur only once');
            });
        }));
    });
    describe('login', () => {
        it('login with token', () => __awaiter(void 0, void 0, void 0, function* () {
            const apolloClient = generateApolloClient({
                path: graphQlPath,
                ssl: ssl,
            });
            const unloginedDeep = new DeepClient({ apolloClient });
            const guest = yield unloginedDeep.guest();
            const guestDeep = new DeepClient(Object.assign({ deep: unloginedDeep }, guest));
            const admin = yield guestDeep.login({
                linkId: yield guestDeep.id('deep', 'admin'),
            });
            const adminToken = admin.token;
            const deep = new DeepClient(Object.assign({ deep: guestDeep }, admin));
            let deepInComponent;
            function DeepConsumerComponent() {
                deepInComponent = useDeep();
                return null;
            }
            render(React.createElement(CapacitorStoreProvider, null,
                React.createElement(QueryStoreProvider, null,
                    React.createElement(CookiesStoreProvider, null,
                        React.createElement(LocalStoreProvider, null,
                            React.createElement(TokenProvider, null,
                                React.createElement(ApolloClientTokenizedProvider, { options: {
                                        client: "@deep-foundation/sdk",
                                        token: adminToken,
                                        path: graphQlPath,
                                        ws: true,
                                    } },
                                    React.createElement(DeepProvider, null,
                                        React.createElement(DeepConsumerComponent, null)))))))));
            yield waitFor(() => {
                assert(deepInComponent.linkId !== 0, 'deep.linkId is 0. Failed to login');
            });
        }));
        it('login with token in apollo client', () => __awaiter(void 0, void 0, void 0, function* () {
            const unloginedDeep = new DeepClient({ apolloClient });
            const guest = yield unloginedDeep.guest();
            const guestDeep = new DeepClient(Object.assign({ deep: unloginedDeep }, guest));
            const admin = yield guestDeep.login({
                linkId: yield guestDeep.id('deep', 'admin'),
            });
            const deepClient = new DeepClient(Object.assign({ deep: guestDeep }, admin));
            assert.isTrue(!!deepClient.token);
            let deepInComponent;
            function TestComponent() {
                deepInComponent = useDeep();
                return null;
            }
            render(React.createElement(QueryStoreProvider, null,
                React.createElement(LocalStoreProvider, null,
                    React.createElement(ApolloClientTokenizedProvider, { options: {
                            path: graphQlPath,
                            ssl: ssl,
                            token: deepClient.token
                        } },
                        React.createElement(TokenProvider, null,
                            React.createElement(DeepProvider, null,
                                React.createElement(TestComponent, null)))))));
            yield waitFor(() => {
                assert(deepInComponent.linkId !== 0, 'deep.linkId is 0. Failed to login');
            });
        }));
    });
});
//# sourceMappingURL=client.react.js.map