import 'reflect-metadata';
require('dotenv').config({ path: `${process.cwd()}/${process.env.ENV_FILE}` });
import 'jest';
import { updateSettingsEpic } from './settings-service';
import { setupReduxApolloStore } from '../__tests__/index';
import gql from 'graphql-tag';
// import { CONFIGURATION_QUERY } from '../graphql/queries';
import { createTestClient } from 'apollo-server-testing';
import preferences from '@workbench-stack/preferences-module-server';
import { ApolloServer } from 'apollo-server';
import { mock } from './__tests__/settings.fixutures';
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
import { CONFIGURATION_QUERY } from '@workbench-stack/preferences-module-browser';
import { logger } from '@cdm-logger/server';

const createStore = (initialState, apolloMocks) =>
    setupReduxApolloStore(typeDefs, updateSettingsEpic, initialState, apolloMocks);

// describe('configuration epic', () => {
//     test('test congiguration', async () => {
//         try {
//             const store = createStore(
//                 {
//                 },
//                 {
//                     Query: () => ({
//                         configuration: () => ({
//                             data: {
//                                 configuration: {
//                                     data: '{\'search\':{\'exclude\':{\'**/node_modules\':true,\'**/bower_components\':true},\'location\':\'sidebar\',\'smartCase\':false,\'useRipgrep\':true,\'useIgnoreFiles\':true,\'followSymlinks\':true,\'globalFindClipboard\':false,\'quickOpen\':{\'includeSymbols\':false}},\'files\':{\'eol\':\'\\n\',\'exclude\':{\'**/.hg\':true,\'**/CVS\':true,\'**/.git\':true,\'**/.svn\':true,\'**/.DS_Store\':true},\'hotExit\':\'onExit\',\'encoding\':\'utf8\',\'autoSave\':\'off\',\'associations\':{},\'autoSaveDelay\':1000,\'watcherExclude\':{\'**/.git/**\':true,\'**/node_modules/**\':true},\'defaultLanguage\':\' \',\'autoGuessEncoding\':false,\'insertFinalNewline\':false,\'trimTrailingWhitespace\':false,\'useExperimentalFileWatcher\':false},\'git\':{\'path\':null,\'enabled\':true,\'autofetch\':false,\'countBadge\':\'all\',\'autorefresh\':true,\'confirmSync\':true,\'checkoutType\':\'all\',\'inputValidation\':\'warn\',\'detectSubmodules\':true,\'enableSmartCommit\':false,\'ignoreLimitWarning\':false,\'ignoreLegacyWarning\':false,\'enableCommitSigning\':false,\'decorations\':{\'enabled\':true},\'defaultCloneDirectory\':null,\'autoRepositoryDetection\':true,\'ignoreMissingGitWarning\':false,\'showInlineOpenFileAction\':true,\'promptToSaveFilesBeforeCommit\':false},\'terminal\':{\'integrated\':{\'shell\':{\'osx\':\'sh\',\'linux\':\'sh\',\'windows\':\'cmd.exe\',\'container\':\'kubectl\'},\'shellArgs\':{\'osx\':[\'-l\'],\'linux\':[],\'windows\':[],\'container\':[\'exec\',\'-it\',\'unkonwn\',\'-n\',\'stackflow1-fad01\',\'-c\',\'dumb-container\',\'/bin/sh\']},\'setLocaleVariables\':false}},\'languages\':{\'go\':false,\'css\':true,\'html\':true,\'json\':true,\'yaml\':true,\'typescript\':false,\'javascript\':false},\'output\':{\'maxChannelHistory\':1000}}',
//                                     // __typename: 'Configuration',
//                                 },
//                             },
//                         }),
//                     }),
//                 },
//             );
//             store.dispatch({ type: 'UPDATE_CONFIGURATION' });
//             console.log('here---');
//             await store.expectActionToBeDispatched('MERGED_CONFIGURATION');
//             console.log(store.getActions());
//         } catch (err) {
//             console.error(err);
//         }
//     });
// });

const rootSchema = `
type Query {
  dummy: Int
}
type Mutation {
  dummy: Int
}
`;
// const resolvers = preferences.createResolvers({ logger, pubsub: undefined });


const typeResolvers = {
    ISettingsSubject: {
        __resolveType(subject, context, info) {
            if (subject.settingsURL.startsWith('file://')) {
                return 'FolderSettings';
            }
            if (subject.settingsURL === 'default') {
                return 'GlobalSettings';
            }
            if (subject.settingsURL === 'user') {
                return 'IUserSettings';
            }
            return null;
        },
    },
};
const typeDefs = rootSchema.concat(preferences.schema as any);
const schema = makeExecutableSchema({
    typeDefs,
    resolvers: typeResolvers,
    resolverValidationOptions: {
        requireResolversForResolveType: true,
    },
});
addMockFunctionsToSchema({
    schema,
    mocks: mock,
    preserveResolvers: true,
});

const server = new ApolloServer({
    schema,
    mocks: mock,
    // mockEntireSchema: false,
    context: () => ({
        preferenceService: {},
        userPreferenceService: {},
    }),
});
const VIEWER_SETTINGS = gql`
query ViewerSettings {
  viewerSettings {
    subjects {
          id
          ... on GlobalSettings {
            settingsCascade {
              final
            }
          }
        }
    final
  }
}
`;

// addMockFunctionsToSchema({
//     schema,
//     mocks: mock,
//     preserveResolvers: true,
// });

it('settings query', async () => {
    const { query } = createTestClient(server);
    const res: any = await query({
        query: VIEWER_SETTINGS,
    });
    logger.info('----res [%j]', res);
    // console.log('----res', res);
});

