"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const reload_1 = __importDefault(require("reload"));
const chokidar_1 = __importDefault(require("chokidar"));
const StaticResourcesUtils_1 = require("../../common/StaticResourcesUtils");
function liveReload(metadataPath, project, config) {
    let reloadReturned;
    let fileWatcher;
    return {
        extendApp: async ({ app }) => {
            reloadReturned = await reload_1.default(app);
            const filesToWatch = getFilesToWatch(metadataPath, project);
            fileWatcher = chokidar_1.default.watch(filesToWatch, {
                ignoreInitial: true
            });
            fileWatcher.on('change', path => {
                if (path && path !== metadataPath) {
                    StaticResourcesUtils_1.rebuildResource(project, config, path);
                }
                else {
                    reloadReturned.reload();
                }
            });
            fileWatcher.on('add', path => {
                StaticResourcesUtils_1.rebuildResource(project, config, path);
            });
            fileWatcher.on('unlink', path => {
                StaticResourcesUtils_1.rebuildResource(project, config, path);
            });
        },
        close: async () => {
            if (reloadReturned) {
                await reloadReturned.closeServer();
            }
            if (fileWatcher) {
                await fileWatcher.close();
            }
        }
    };
}
exports.liveReload = liveReload;
function getFilesToWatch(metadataPath, project) {
    let filesToWatch = [metadataPath];
    const staticResources = project.staticResourcesDirectories;
    if (staticResources && staticResources.length > 0) {
        staticResources.forEach((item) => {
            filesToWatch.push(item);
        });
    }
    const contentAssetsDir = project.contentAssetsDirectory;
    if (contentAssetsDir && contentAssetsDir !== '') {
        filesToWatch.push(contentAssetsDir);
    }
    return filesToWatch;
}
exports.getFilesToWatch = getFilesToWatch;
//# sourceMappingURL=liveReload.js.map