"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const schematics_1 = require("@angular-devkit/schematics");
const utility_1 = require("@schematics/angular/utility");
const helper_1 = require("../helper/helper");
function updateAngularJson(tree, options) {
    const angularJsonPath = `angular.json`;
    if (!tree.exists(angularJsonPath)) {
        throw new Error(`${angularJsonPath} not found`);
    }
    const angularJsonContent = tree.read(angularJsonPath)?.toString('utf-8');
    if (!angularJsonContent) {
        throw new Error(`Failed to read ${angularJsonPath}`);
    }
    const angularJson = JSON.parse(angularJsonContent);
    const project = options.project || Object.keys(angularJson.projects)[0];
    if (!angularJson.projects[project]) {
        throw new Error(`Project ${project} not found in angular.json`);
    }
    const buildOptions = angularJson.projects[project].architect.build.options;
    buildOptions.assets = buildOptions.assets || [];
    const pdfViewerAsset = {
        glob: '**/*',
        input: 'node_modules/ngx-extended-pdf-viewer/assets/',
        output: '/assets/'
    };
    const assetIndex = buildOptions.assets.findIndex((asset) => typeof asset === 'object' && asset.glob === pdfViewerAsset.glob && asset.input === pdfViewerAsset.input && asset.output === pdfViewerAsset.output);
    if (assetIndex !== -1) {
        buildOptions.assets.splice(assetIndex, 1);
    }
    buildOptions.allowedCommonJsDependencies = buildOptions.allowedCommonJsDependencies || [];
    ['pdfjs-dist', 'pdfjs-dist/web/pdf_viewer'].map((dep) => buildOptions.allowedCommonJsDependencies?.push(dep));
    tree.overwrite(angularJsonPath, JSON.stringify(angularJson, null, 2));
    return tree;
}
exports.default = (options) => {
    return async (tree, ctx) => {
        if (tree.exists('package.json')) {
            const json = (0, helper_1.readSourceFile)(tree, 'package.json');
            const versionNumber = (0, helper_1.getVersion)(json);
            if (versionNumber < 15) {
                throw new schematics_1.SchematicsException('This Angular version is not Supported. Please refer to @yuuvis/project');
            }
            //  else if (versionNumber > 19) {
            //   throw new SchematicsException('This Angular version is not yet Supported. We are working on it realy Hard!');
            // }
        }
        else {
            throw new schematics_1.SchematicsException("We coudn't find the package JSON");
        }
        const workspace = await (0, utility_1.readWorkspace)(tree);
        const project = workspace.projects.get(options.project);
        options.sourceRoot = project?.sourceRoot;
        options.root = project?.root;
        return (0, schematics_1.chain)([() => (tree) => updateAngularJson(tree, options)]);
    };
};
//# sourceMappingURL=index.js.map