import extend from '@techor/extend';

// todo: split resolveConfig into a function
function extendConfig(...configs) {
    const formatConfig = (config)=>{
        const clonedConfig = extend({}, config);
        const formatDeeply = (obj)=>{
            for(const key in obj){
                const value = obj[key];
                if (typeof value === 'object' && !Array.isArray(value)) {
                    formatDeeply(value);
                } else if (key && !key.startsWith('@')) {
                    obj[key] = {
                        '': value
                    };
                }
            }
        };
        if (clonedConfig.styles) {
            formatDeeply(clonedConfig.styles);
        }
        if (clonedConfig.at) {
            formatDeeply(clonedConfig.at);
        }
        if (clonedConfig.variables) {
            formatDeeply(clonedConfig.variables);
        }
        return clonedConfig;
    };
    const formattedConfigs = [];
    for (const eachConfig of configs){
        if (!eachConfig) continue;
        (function getConfigsDeeply(config) {
            if (config.extends?.length) {
                for (const eachExtend of config.extends){
                    getConfigsDeeply('config' in eachExtend ? eachExtend.config : eachExtend);
                }
            }
            formattedConfigs.push(formatConfig(config));
        })(eachConfig);
    }
    let extendedConfig = {
        animations: {},
        styles: {},
        at: {},
        variables: {}
    };
    for(let i = 0; i < formattedConfigs.length; i++){
        const currentFormattedConfig = formattedConfigs[i];
        for(const key in currentFormattedConfig){
            switch(key){
                case 'animations':
                    if (currentFormattedConfig.animations) {
                        Object.assign(extendedConfig.animations, currentFormattedConfig.animations);
                    }
                    break;
                default:
                    if (currentFormattedConfig[key]) {
                        extendedConfig = extend(extendedConfig, {
                            [key]: currentFormattedConfig[key]
                        });
                    }
            }
        // if (Object.prototype.hasOwnProperty.call(currentFormattedConfig.styles, key)) {
        //     Object.assign(extendedConfig.styles[key], currentFormattedConfig.styles[key])
        // }
        }
    }
    return extendedConfig;
}

export { extendConfig as default };
