"use strict";
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const clear_require_1 = require("clear-require");
const path_1 = require("path");
const getScriptFileNames_1 = require("../cli/getScriptFileNames");
const makeAbsolute_1 = require("../common/makeAbsolute");
const createLanguageService_1 = require("../typescript/createLanguageService");
const findNode_1 = require("../typescript/findNode");
const isTypedTestTestInterface_1 = require("../typescript/isTypedTestTestInterface");
const registerTsPaths_1 = require("../typescript/registerTsPaths");
const transpileNode_1 = require("../typescript/transpileNode");
const findMetadataFromProgram_1 = require("./findMetadataFromProgram");
const parseTestMetadata_1 = require("./parseTestMetadata");
// tslint:disable-next-line:no-var-requires
const watch = require('glob-watcher');
function watchTestMetadata(cwd, fileGlobs, compilerOptions, mode, logger, removeFile, cb) {
    if (mode === 'node') {
        registerTsPaths_1.registerTsPaths(compilerOptions);
        transpileNode_1.transpileNode(cwd, compilerOptions);
    }
    return watchMetadata(cwd, fileGlobs, compilerOptions, mode, logger, cb, removeFile);
}
exports.watchTestMetadata = watchTestMetadata;
function watchMetadata(cwd, fileGlobs, compilerOptions, mode, logger, cb, removeFile) {
    return __awaiter(this, void 0, void 0, function* () {
        const files = {};
        const filePaths = getScriptFileNames_1.getScriptFileNames(cwd, fileGlobs).map(x => makeAbsolute_1.makeAbsolute(cwd, x));
        filePaths.forEach(filePath => {
            files[filePath] = { version: 0 };
        });
        const services = createLanguageService_1.createLanguageService(cwd, fileGlobs, compilerOptions, files);
        const program = services.getProgram();
        const typeChecker = program.getTypeChecker();
        const typedTestInterface = yield findNode_1.findNode(isTypedTestTestInterface_1.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_1.makeAbsolute(cwd, x.fileName) === filePath);
                if (userSourceFiles.length === 0) {
                    return;
                }
                logger.log('Updating ' + path_1.relative(cwd, filePath));
                const metadata = parseTestMetadata_1.parseTestMetadata(userSourceFiles, typedTestSymbol, typeChecker).map(m => (Object.assign({}, m, { filePath: makeAbsolute_1.makeAbsolute(cwd, m.filePath) })));
                cb(metadata);
            });
        }
        const watcher = watch(fileGlobs, { cwd });
        yield logger.log('Finding metadata...');
        return findMetadataFromProgram_1.findMetadataFromProgram(filePaths, services.getProgram())
            .then(cb)
            .then(() => {
            watcher.on('change', (filePath) => updateFile(makeAbsolute_1.makeAbsolute(cwd, filePath), false));
            watcher.on('add', (filePath) => updateFile(makeAbsolute_1.makeAbsolute(cwd, filePath), true));
            // On file deleted
            watcher.on('unlink', (filePath) => {
                if (mode === 'node') {
                    clear_require_1.all();
                }
                const absolutePath = makeAbsolute_1.makeAbsolute(cwd, filePath);
                if (files[absolutePath]) {
                    delete files[absolutePath];
                }
                removeFile(absolutePath);
            });
            return { dispose: () => watcher.close() };
        });
    });
}
function clear(mode) {
    if (mode === 'node') {
        clear_require_1.all();
    }
}
//# sourceMappingURL=watchTestMetadata.js.map