var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { all } from 'clear-require';
import { relative } from 'path';
import { getScriptFileNames } from '../cli/getScriptFileNames';
import { makeAbsolute } from '../common/makeAbsolute';
import { createLanguageService } from '../typescript/createLanguageService';
import { findNode } from '../typescript/findNode';
import { isTypedTestTestInterface } from '../typescript/isTypedTestTestInterface';
import { registerTsPaths } from '../typescript/registerTsPaths';
import { transpileNode } from '../typescript/transpileNode';
import { findMetadataFromProgram } from './findMetadataFromProgram';
import { parseTestMetadata } from './parseTestMetadata';
// tslint:disable-next-line:no-var-requires
const watch = require('glob-watcher');
export function watchTestMetadata(cwd, fileGlobs, compilerOptions, mode, logger, removeFile, cb) {
    if (mode === 'node') {
        registerTsPaths(compilerOptions);
        transpileNode(cwd, compilerOptions);
    }
    return watchMetadata(cwd, fileGlobs, compilerOptions, mode, logger, cb, removeFile);
}
function watchMetadata(cwd, fileGlobs, compilerOptions, mode, logger, cb, removeFile) {
    return __awaiter(this, void 0, void 0, function* () {
        const files = {};
        const filePaths = getScriptFileNames(cwd, fileGlobs).map(x => makeAbsolute(cwd, x));
        filePaths.forEach(filePath => {
            files[filePath] = { version: 0 };
        });
        const services = createLanguageService(cwd, fileGlobs, compilerOptions, files);
        const program = services.getProgram();
        const typeChecker = program.getTypeChecker();
        const typedTestInterface = yield findNode(isTypedTestTestInterface(typeChecker), program.getSourceFiles());
        const typedTestSymbol = typeChecker.getTypeAtLocation(typedTestInterface).getSymbol();
        function updateFile(filePath, added) {
            return __awaiter(this, void 0, void 0, function* () {
                clear(mode);
                if (added) {
                    files[filePath] = { version: 0 };
                }
                else {
                    files[filePath].version++;
                }
                const program = services.getProgram(); // required - side-effectful
                const userSourceFiles = program
                    .getSourceFiles()
                    .filter(x => makeAbsolute(cwd, x.fileName) === filePath);
                if (userSourceFiles.length === 0) {
                    return;
                }
                logger.log('Updating ' + relative(cwd, filePath));
                const metadata = parseTestMetadata(userSourceFiles, typedTestSymbol, typeChecker).map(m => (Object.assign({}, m, { filePath: makeAbsolute(cwd, m.filePath) })));
                cb(metadata);
            });
        }
        const watcher = watch(fileGlobs, { cwd });
        yield logger.log('Finding metadata...');
        return findMetadataFromProgram(filePaths, services.getProgram())
            .then(cb)
            .then(() => {
            watcher.on('change', (filePath) => updateFile(makeAbsolute(cwd, filePath), false));
            watcher.on('add', (filePath) => updateFile(makeAbsolute(cwd, filePath), true));
            // On file deleted
            watcher.on('unlink', (filePath) => {
                if (mode === 'node') {
                    all();
                }
                const absolutePath = makeAbsolute(cwd, filePath);
                if (files[absolutePath]) {
                    delete files[absolutePath];
                }
                removeFile(absolutePath);
            });
            return { dispose: () => watcher.close() };
        });
    });
}
function clear(mode) {
    if (mode === 'node') {
        all();
    }
}
//# sourceMappingURL=watchTestMetadata.js.map