import gql from 'graphql-tag';
import { ApolloLink, Operation } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { stripSymbols } from 'apollo-utilities';
import { DocumentNode, OperationDefinitionNode } from 'graphql';
import { ApolloClient } from 'apollo-client';
import { mockSingleLink, mockObservableLink } from '../../__mocks__/mockLinks';
import { FileContent_WsDocument, createTextFileContentProvider, FileDataSubscription } from './text-file-content-provider-mock';
import { ModeService } from '../mode-service';
import { ModelService } from '../model-service';
import { URI } from '@vscode/monaco-editor/esm/vs/base/common/uri';
// import { IFileOperation as FileOperation } from '@files-stack/client-state';
import 'jest';
// https://github.com/apollographql/apollo-client/blob/master/packages/apollo-client/src/__tests__/subscribeToMore.ts
const isSub = (operation: Operation) =>
    (operation.query as DocumentNode).definitions
        .filter(x => x.kind === 'OperationDefinition')
        .some((x: OperationDefinitionNode) => x.operation === 'subscription');

describe('text-file-content-provider-mock', () => {

    const result = {
        data: {
            entry: {
                value: '1',
            },
        },
    };

    const results  =  ['a', 'b', 'c'].map(name => ({
        result: {
            data: {
                fileData: [
                    {
                        name,
                        resource: 'file:///test',
                    },
                ],
            } as FileDataSubscription,
        },
        delay: 10,

    }));

    const req1 = { request: { query: FileContent_WsDocument } as Operation, result };
    // const operationReq = { request: { query: }}

    it('trigger new result', async done => {
        const wSLink = mockObservableLink();
        const httpLink = mockSingleLink(req1);

        const link = ApolloLink.split(isSub, wSLink, httpLink);

        const client = new ApolloClient({
            cache: new InMemoryCache({ addTypename: false }),
            link,
        });

        const textFileContentProvider  = createTextFileContentProvider(client, new ModelService(), new ModeService());

        const resourceUri = URI.revive({
            file: 'file',
            scheme: 'file',
            path: '/test',
            query: '{"scheme":"file"}',
        });

        console.log('----res', resourceUri);
        const testContent = await textFileContentProvider.provideTextContent(resourceUri);
        console.log('--testContent', testContent.uri);

        setTimeout(() => {
            done();
        }, 200);
        for (let i = 0; i < 2; i++) {
            wSLink.simulateResult(results[i]);
        }
    });
});
