const lodash = require('lodash');

const externals = [
    libExternalFactory(),
    ngExternalsFactory(),
    rxjsExternalsFactory(),
    mggExternalsFactory(),
    // kendoExternalsFactory(),
]

function libExternalFactory() {
    return function(_context, request, callback) {

        const value = lodash.toString(request)

        if ((/^(zone|jquery|lodash|moment)$/i).test(value)) {
            return callback(null, externalsObject(value))
        }

        return callback()
    }
}

function ngExternalsFactory() {
    return function(_context, request, callback) {
        if (lodash.startsWith(request, '@angular/')) {

            const temp = lodash.map(lodash.split(request, '/'), camelCase)
            const value = lodash.join(['ng', ...temp.slice(1)], '.')

            if (value === 'ng.common.locales.it') { return callback() }
            if (value === 'ng.common.locales.extra.it') { return callback() }

            return callback(null, externalsObject(value))
        }

        return callback()
    }
}

function rxjsExternalsFactory() {
    return function rxjsExternals(_context, request, callback) {
        if (request.match(/^rxjs(\/|$)/)) {

            const parts = lodash.split(request, '/')
            const value = lodash.join(parts, '.')

            if (lodash.size(parts) <= 2) {
                return callback(null, externalsObject(value))
            }
        }

        return callback();
    }
}

function mggExternalsFactory() {
    return function mggExternals(_context, request, callback) {
        if (lodash.startsWith(request, '@maggioli/')) {
            return callback(null, externalsObject(
                lodash.camelCase(lodash.tail(lodash.split(request, '/')))
            ))
        }
        return callback();
    }
}

function camelCase(val) { return (val === 'a11y') ? val : lodash.camelCase(val) }

function externalsObject(value) { return { root: value, var: value } }

function noParseExternals(content) {

    if (/^(zone|jquery|lodash|moment)$/i.test(content)) { return true }

    return false
}

module.exports = {
    mode: 'production', externals,
    output: {
        libraryTarget: 'var',
        library: 'stc',
    },
    module: { noParse: noParseExternals },
}