/* global registerGlobalBackward, TraverseUtility, DataProviderFacade */
registerGlobalBackward('4.5.20', function (theme) {
    'use strict';
    if(theme.constructorName !== 'Theme') {
        return theme;
    }
    if (DataProviderFacade.getCmsInfo().cmsName === 'Html') {
        var hasSidebars = function hasSidebars(sidebars) {
            return !(sidebars.left === '' && sidebars.right === '' && sidebars.top === '' && sidebars.topWide === ''&& sidebars.bottom === '' && sidebars.bottomWide === '');
        };
        var getContentControl = function getContentControl(contentLayout) {
            var contentControl;
            if (contentLayout.content && contentLayout.content.items && contentLayout.content.items.length) {
                var items = contentLayout.content.items;
                for (var index in items) {
                    if (items.hasOwnProperty(index) && 'string' === typeof items[index]) {
                        var control = theme.controls[items[index].replace('/controls/', '')];
                        if (control && control.constructorName === 'Content') {
                            contentControl = items[index];
                            break;
                        }
                    }
                }
            }
            return contentControl;
        };
        TraverseUtility.traverseControls(theme.controls, function (control, property) {
            if (control.constructorName === 'ContentLayout' && !hasSidebars(control)) {
                var placeholder = '/controls/' + property;
                var collections = TraverseUtility.getCollectionsWithElement(theme, placeholder);
                var contentControl = getContentControl(control);
                if (contentControl) {
                    collections.forEach(function (collection) {
                        var index;
                        for (var _index in collection) {
                            if (collection.hasOwnProperty(_index) && 'string' === typeof collection[_index] && collection[_index] === placeholder) {
                                index = _index;
                                break;
                            }
                        }
                        if (index) {
                            collection[index] = contentControl;
                            delete theme.controls[property];
                        }
                    });
                }
            }
        });
    }
    return theme;
});