/* global registerGlobalBackward, TraverseUtility, AppSettings */

registerGlobalBackward('3.3.0', function (theme) {
    'use strict';

    if (theme.constructorName !== 'Theme') return theme;

    var deletedControls,
        controlsToDelete = ['CartLink', 'CartBlock','CartGrid'];

    do {
        /* jshint -W083 */
        deletedControls = [];
        controlsToDelete.forEach(function (constructor) {
            Object.keys(theme.controls).forEach(function (key) {
                if (constructor === theme.controls[key].constructorName) {
                    if (!inLayout('/controls/' + key)) {
                        deletedControls.push(key);
                        delete theme.controls[key];
                    }
                }
            });
        });
        if (deletedControls.length && AppSettings.isDebug) {
            console.log('%cDeleted controls: ' + deletedControls.join(', '), 'color: #bada55');
        }
        /* jshint +W083 */
    } while (deletedControls.length > 0);

    function inLayout(placeholder) {
        var found = false;
        TraverseUtility.traverseControls(theme, function (control) {
            if (!found && control.length) {
                for (var i = 0; i < control.length; i++) {
                    if (control[i] === placeholder) {
                        found = true;
                        break;
                    }
                }
            }
            return !found;
        });
        return found;
    }

    return theme;
});