
import { ITextFileService } from '@workbench-stack/core';
import { URI } from '@vscode/monaco-editor/esm/vs/base/common/uri';
import { ApolloClient } from 'apollo-client';
import { Observable, of, Subscribable, from } from 'rxjs';
import {
    CacheTypenames,
} from '@files-stack/client-state';
import { IFilesConfiguration, AutoSaveMode, ITextSnapshot,
    ISaveFileMutationVariables, SaveFileDocument, ISaveFileMutation, ChangeDirtyStateOnFileStatFragmentDoc,
 } from '@files-stack/core';
import { ICreateFileOptions } from '@vscode/monaco-editor/esm/vs/platform/files/common/files';
import { StaticServices } from '@vscode/monaco-editor/esm/vs/editor/standalone/browser/standaloneServices';

export function createTextFileService(apolloClient: ApolloClient<any>): ITextFileService| any {

    function saveTextFile(resource, options) {
        return apolloClient.mutate<ISaveFileMutation, ISaveFileMutationVariables>({
            mutation: SaveFileDocument,
            variables: {
                resource: resource,
                options,
            },
        });
    }

    function resolveTextFile(resource, options) {

    }

    function getDirty(resources?: URI[]): URI[] {
        let inputs;
        if (resources) {
            inputs = resources.map(resource => {
                const id = `${CacheTypenames.FileStat}:${resource}`;
                const fileStat = apolloClient.readFragment({
                    fragment: ChangeDirtyStateOnFileStatFragmentDoc,
                    id,
                    variables: {
                        resource,
                    },
                });
                return fileStat.isDirty;
            });
        } else {
            inputs = [];
            // TODO write a resolver in files stack to search from all URIs

            // apolloClient.readQuery({
            //     query: '',

            // })
        }
        return inputs;
    }

    function isDirty(resource?: URI): boolean {
        const id = `${CacheTypenames.FileStat}:${resource}`;
        const fileStat = apolloClient.readFragment({
            fragment: ChangeDirtyStateOnFileStatFragmentDoc,
            id,
            variables: {
                resource,
            },
        });
        console.log('[check>>>] textFileService: ', { fileStat, resource });
        return fileStat ? fileStat.isDirty : false;
    }

    async function create(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions) {
        const stat = await doCreate(resource, value, options);

        // If we had an existing model for the given resource, load
        // it again to make sure it is up to date with the contents
        // we just wrote into the underlying resource by calling
        // revert()

        const existingModel = StaticServices.modelService.get().getModel(resource);
        if (existingModel && !existingModel.isDisposed()) {
            // await existingModel.revert();
        }
        return stat;
    }

    function doCreate(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions) {
        // return apolloClient.mutate({
        //     mutation: '',
        //     variables: {

        //     },
        // });
    }

    function write(resource: URI, value: string | ITextSnapshot, options) {
        // return apolloClient.mutate({
        //     mutation: 'FILE',
        //     variables: {
        //         resource,
        //         data: toBufferOrReadable(value),
        //         options,
        //     },
        // });
    }

    function doDelete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): Promise<void> | any {
        // get dirty files
        // save them
        console.log('not yet implemented');

    }

    return {
        saveTextFile,
        isDirty,
        getDirty,
    };
}

