/* global registerBackward, TraverseUtility, GoogleFontsController */
registerBackward('1.18.13', 'Theme', function (theme) {
    'use strict';
    TraverseUtility.traverseControls(theme.controls, fixGoogleFontsFamilies);
    TraverseUtility.traverseControls(theme.templates, fixGoogleFontsFamilies);
    TraverseUtility.traverseControls(theme.prototypes, fixGoogleFontsFamilies);

    function fixGoogleFontsFamilies(control) {
        if (control.css && control.css['font-family']){
            GoogleFontsController.addFamily(control.css['font-family'], '');
        }

        if (control.css && control.css.typography && Object.keys(control.css.typography).length) {
            var typographies = control.css.typography;
            for (var typography in typographies) {
                if (typographies.hasOwnProperty(typography) && typographies[typography]['font-family']) {
                    GoogleFontsController.addFamily(typographies[typography]['font-family'], '');
                }
            }
        }
        if (control.content) {
            var fontFace = /<font face="([^"]*)">/g;
            var content = control.content;
            var fontArray;
            while ((fontArray = fontFace.exec(content)) !== null) {
                if (fontArray.length > 1) {
                    GoogleFontsController.addFamily(fontArray[1], '');
                }
            }
        }
    }
    return theme;
});