import { URI } from '@vscode/monaco-editor/esm/vs/base/common/uri';
import { ITextModelContentProvider } from '@vscode/monaco-editor/esm/vs/editor/common/services/resolverService';
import { ApolloClient } from 'apollo-client';
import { IModelService, IModeService } from '@workbench-stack/core';
import { ILanguageSelection } from '@vscode/monaco-editor/esm/vs/editor/common/services/modeService';
// import { IFileDataSubscription } from '@files-stack/client-state';
import gql from 'graphql-tag';

export const FileContent_WsDocument = gql`
    query aQuery {
        entry {
            value
        }
    }
`;


export const FileOperationDocument = gql`
    subscription aQuery {
                type
                resource
    }
`;
export type FileDataSubscription = IFileDataSubscription;

export const FileContent_Document = gql`
    subscription newValues {
        name
    }
`;

export type FileContent_WsQuery =  {
    entry: {
        value: string;
    },
};


interface SubscriptionData {
    name: string;
}

export function createTextFileContentProvider(apolloClient: ApolloClient<any>, modelService: IModelService, modeService: IModeService) {

    const subscribeFileChange = apolloClient.subscribe<FileDataSubscription>({
        query: FileOperationDocument,
    }).subscribe({
        next(result) {
           console.log('----subscribedFilechange', result);
        },
    });
    function resourceToTextFile(scheme: string, resource: URI): URI {
        return resource.with({ scheme, query: JSON.stringify({ scheme: resource.scheme }) });
    }

    function textFileToResource(resource: URI): URI {
        console.log('---uri', resource);
        return resource.with({ scheme: JSON.parse(resource.query)['scheme'], query: null });
    }

    async function resolveEditorModel(resource: URI, createAsNeeded: boolean = true) {
        const savedFileResource = textFileToResource(resource);

        const content = await apolloClient.query<FileContent_WsQuery>({
            query: FileContent_WsDocument,
        });
        // const contentSub = content.subscribe({
        //     next(queryResult) {
        //         // latestResult = queryResult;
        //         console.log('----queryResult --latest', queryResult);
        //     },
        // });
        // content.subscribeToMore<SubscriptionData>({
        //     document: FileContent_Document,
        //     updateQuery: (_, { subscriptionData }) => {
        //         return { entry: { value: subscriptionData.data.name } };
        //     },
        //     onError: () => {
        //         console.log('---errorr');
        //     },
        // });

        let codeEditorModel = modelService.getModel(resource);

        if (codeEditorModel) {
            modelService.updateModel(codeEditorModel, content.data.entry.value);
        } else if (createAsNeeded) {
            const textFileModel = modelService.getModel(savedFileResource);
            let languageSelector: ILanguageSelection;
            if (textFileModel) {
                languageSelector = modeService.create(textFileModel.getModeId());
            } else {
                languageSelector = modeService.createByFilepathOrFirstLine(savedFileResource.path);
            }

            codeEditorModel = modelService.createModel(content.data.entry.value, languageSelector, resource);
        }

        return codeEditorModel;
    }
    return {
        provideTextContent(resource: URI) {
            const savedFileResource = textFileToResource(resource);

            // Make sure our text file is resolved up to date
            const codeEditorModel = resolveEditorModel(resource);

            return codeEditorModel;
        },
    };

}
