const plugin = (options = {blocks: []}) => {
    return {
        postcssPlugin: 'postcss-remove-bem-blocks',
        Rule(rule) {
            options.blocks.forEach((block) => {
                if (rule.selector.includes(block)) {
                    const regexp = new RegExp(`${block}(?![A-Za-z0-9-]+)`);
                    if (rule.selectors.length === 1) {
                        if (regexp.test(rule.selectors[0])) {
                            rule.remove();
                        }
                    } else {
                        const selectors = [];
                        rule.selectors.forEach((selector) => {
                            if (!regexp.test(selector)) {
                                selectors.push(selector);
                            }
                        });
                        if (selectors.length) {
                            const cloned = rule.clone();
                            cloned.selectors = selectors;
                            rule.replaceWith(cloned);
                        } else {
                            rule.remove();
                        }
                    }
                }
            });
        },
    };
};

plugin.postcss = true;

export default plugin;
