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

const ALLOWED_PROPERTIES = [
    "name",
    "private",
    "version",
    "description",
    "author",
    "license",
    "dependencies",
    "devDependencies"
];

const DEPENDENCY_FILTER = dep => dep.indexOf('@atlassian/') === -1;

module.exports = function (gulp, paths) {
    return function (cb) {
        const json = JSON.parse(fs.readFileSync(paths.PACKAGE_JSON, 'utf-8'));
        const strippedJson = Object.keys(json)
            .filter(key => ALLOWED_PROPERTIES.indexOf(key) !== -1)
            .reduce((out, key) => {
                if (/dependencies$/i.test(key)) {
                    out[key] = Object.keys(json[key])
                        .filter(DEPENDENCY_FILTER)
                        .reduce((out, dep) => {
                                out[dep] = json[key][dep];
                                return out;
                            }, {});
                } else {
                    out[key] = json[key];
                }
                return out;
            }, {});
        const filename = path.basename(paths.PACKAGE_JSON);
        fs.writeFileSync(path.join(paths.WEBAPP_TARGET, filename), JSON.stringify(strippedJson));
        cb();
    }
};