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 { FileContent_WsDocument, FileContent_WsQuery, FileOperationSubscription, FileOperationDocument } from '@files-stack/client-state';




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

    const subscribeFileChange = apolloClient.subscribe<FileOperationSubscription>({
        query: FileOperationDocument,
    });
    function resourceToTextFile(scheme: string, resource: URI): URI {
        return resource.with({ scheme, query: JSON.stringify({ scheme: resource.scheme }) });
    }

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

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

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

        let codeEditorModel = modelService.getModel(resource);

        if (codeEditorModel) {
            modelService.updateModel(codeEditorModel, content.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.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);
        },
    };

}
