import { BehaviorSubject, Subject } from 'rxjs';
import { chokidar, ___NS__isBoolean, CoreModels__NS__BuildTypeArr, CoreModels__NS__buildTypeToWatcherFn, CoreModels__NS__BuildWatcherTypeArr } from 'tnp-core/lib-prod';
import { crossPlatformPath, path } from 'tnp-core/lib-prod';
import { BaseFeatureForProject, Helpers__NS__logInfo, Helpers__NS__warn } from 'tnp-helpers/lib-prod';
import { assetsFromTempSrc, tmpSourceDist, tmpSrcDist, tmpSrcDistWebsql, } from '../../constants';
// @ts-ignore TODO weird inheritance problem
export class LightWeightWatcher extends BaseFeatureForProject {
    //#region fields
    codeWatchers = new Map();
    rebuildWatchers = new Map();
    //#endregion
    //#region public methods
    //#region public methods / is taon light weight mode allowed
    get isTaonLightWatcherMode() {
        //#region @backendFunc
        if (___NS__isBoolean(global.oldBuildModeInArgs)) {
            return !global.oldBuildModeInArgs;
        }
        return true;
        //#endregion
    }
    //#endregion
    //#region public methods / trigger rebuild of
    triggerRebuildOf(buildType) {
        //#region @backendFunc
        if (!buildType ||
            !CoreModels__NS__BuildWatcherTypeArr.includes(CoreModels__NS__buildTypeToWatcherFn(buildType))) {
            Helpers__NS__warn(`[triggerRebuildOf] Wrong trigger "${buildType}"`);
            return;
        }
        Helpers__NS__logInfo(`TRIGGER REBUILD ${buildType}`);
        this.rebuildTriggerWatcher(buildType).next({});
        //#endregion
    }
    //#endregion
    //#region public methods / trigger rebuild of
    cancelAndSetAsReadyForRebuildTrigger(buildType) {
        //#region @backendFunc
        if (!buildType || !CoreModels__NS__BuildTypeArr.includes(buildType)) {
            Helpers__NS__warn(`[cancelAndSetAsReadyForRebuildTrigger] Wrong trigger "${buildType}"`);
            return;
        }
        // TODO @LAST
        //#endregion
    }
    //#endregion
    //#region public methods / get rebuild trigger watcher
    rebuildTriggerWatcher(buildType) {
        //#region @backendFunc
        if (!this.isTaonLightWatcherMode) {
            return;
        }
        if (!this.rebuildWatchers.has(buildType)) {
            const subject = new BehaviorSubject({});
            this.rebuildWatchers.set(buildType, subject);
        }
        return this.rebuildWatchers.get(buildType);
        //#endregion
    }
    //#endregion
    //#region public methods / get ts code obserable for
    getTsCodeObservableFor(buildType) {
        if (buildType === 'backend-watcher') {
            return this.tmpSourceRebuildForBackendObs;
        }
        if (buildType === 'browser-watcher') {
            return this.tmpSourceRebuildForBrowserObs;
        }
        if (buildType === 'websql-watcher') {
            return this.tmpSourceRebuildForWebsqlObs;
        }
    }
    //#endregion
    //#endregion
    //#region private methods
    //#region private methods / get watcher for
    /**
     * Get source code watcher obserable watcher
     */
    getWatcherFor(folders, watcherType) {
        //#region @backendFunc
        if (this.codeWatchers.has(watcherType)) {
            return this.codeWatchers.get(watcherType).asObservable();
        }
        const watcher = new Subject();
        this.codeWatchers.set(watcherType, watcher);
        // const isomorphic = this.project.nodeModules.getIsomorphicPackagesNames();
        // console.log({ isomorphic });
        const pathsToWatch = [
            ...folders,
            // ...isomorphic.map(p =>
            //   this.project.nodeModules.pathFor([p, packageJsonNpmLib]),
            // ),
        ];
        // console.log('Watching for changes in:', pathsToWatch);
        chokidar
            .watch(pathsToWatch, {
            ignoreInitial: true,
        })
            .on('all', async (eventWatcher, pathToFile) => {
            const relative = crossPlatformPath(pathToFile).replace(this.project.location + '/' + path.basename(folders[0]) + '/', '');
            if (watcherType === 'backend-watcher') {
                if (!relative.startsWith(`${assetsFromTempSrc}/`)) {
                    // console.log('WATCHER CHANGE', {
                    //   eventWatcher,
                    //   pathToFile,
                    //   watcherType,
                    // });
                    watcher.next({});
                }
            }
            else {
                if (!relative.startsWith(`${assetsFromTempSrc}/`) &&
                    !relative.startsWith(`app/`) &&
                    !relative.startsWith(`app.`)) {
                    // console.log('WATCHER CHANGE', {
                    //   eventWatcher,
                    //   pathToFile,
                    //   watcherType,
                    // });
                    watcher.next({});
                }
            }
        });
        return watcher.asObservable();
        //#endregion
    }
    //#endregion
    //#region private methods / tmp srouce obserable
    get tmpSourceRebuildForBackendObs() {
        const key = 'tmpSourceRebuildForBackendObs';
        if (this.project.cache[key]) {
            return this.project.cache[key];
        }
        const watcher = this.getWatcherFor([this.project.pathFor(tmpSourceDist)], 'backend-watcher');
        this.project.cache[key] = watcher;
        return this.project.cache[key];
    }
    get tmpSourceRebuildForBrowserObs() {
        const key = 'tmpSourceRebuildForBrowserObs';
        if (this.project.cache[key]) {
            return this.project.cache[key];
        }
        const watcher = this.getWatcherFor([this.project.pathFor(tmpSrcDist)], 'browser-watcher');
        this.project.cache[key] = watcher;
        return this.project.cache[key];
    }
    get tmpSourceRebuildForWebsqlObs() {
        const key = 'tmpSourceRebuildForWebsqlObs';
        if (this.project.cache[key]) {
            return this.project.cache[key];
        }
        const watcher = this.getWatcherFor([this.project.pathFor(tmpSrcDistWebsql)], 'websql-watcher');
        this.project.cache[key] = watcher;
        return this.project.cache[key];
    }
}
//# sourceMappingURL=lightweight-watcher.js.map