#!/usr/bin/env node

const path = require("path");
const fs = require("fs");

const browserDynamicDependency = "@angular/platform-browser-dynamic";
const binPath = __dirname;
const pluginPath = path.dirname(binPath);
const pluginPackageJsonPath = path.join(pluginPath, "package.json");
const pluginPackageJson = JSON.parse(fs.readFileSync(pluginPackageJsonPath, "utf8"));

const isNgDependency = name => name.startsWith("@angular") ||
    name === "rxjs" ||
    name === "zone.js";

function updateDeps(deps, newDeps) {
    // set app dependencies to ones required from plugin
    Object.keys(newDeps)
        .filter(isNgDependency)
        .filter(dependencyName => deps.hasOwnProperty(dependencyName))
        .map(dependencyName => ({
            dependencyName,
            version: pluginPackageJson.peerDependencies[dependencyName]
        }))
        .filter(({ dependencyName, version }) => deps[dependencyName] !== version)
        .forEach(({ dependencyName, version }) => {
            deps[dependencyName] = version;
            console.log(`Updated dependency ${dependencyName} to version: ${version}.`);
        });
    
    // remove platform-browser-dynamic if present
    if (deps.hasOwnProperty(browserDynamicDependency)) {
        delete deps[browserDynamicDependency];
        console.log(`Removed ${browserDynamicDependency}`);
    }


    return deps;
}

let pluginDeps = pluginPackageJson.peerDependencies;
Object.keys(pluginPackageJson.devDependencies)
    .filter(isNgDependency)
    .filter(depName => !pluginDeps.hasOwnProperty(depName))
    .forEach(depName => {
        pluginDeps[depName] = pluginPackageJson.devDependencies[depName];
    });

const projectPath = path.dirname(path.dirname(pluginPath));
const appPackageJsonPath = path.join(projectPath, "package.json");
const appPackageJson = JSON.parse(fs.readFileSync(appPackageJsonPath, "utf8"));

appPackageJson.dependencies = updateDeps(appPackageJson.dependencies, pluginDeps);
appPackageJson.devDependencies = updateDeps(appPackageJson.devDependencies, pluginDeps);

fs.writeFileSync(appPackageJsonPath, JSON.stringify(appPackageJson, null, 2));

console.log("\nAngular dependencies updated. Don't forget to run `npm install`.");
