/* global registerBackward */

registerBackward('1.9.2', function (control) {
    'use strict';

    var suffix = {
        '': 'Passive',
        'hover': 'Hovered',
        'active': 'Active',
        'visited': 'Visited'
    };

    function traverseCss(css) {
        if (typeof css !== 'object') return;

        if (css.typography) {
            moveTypography(css.typography, css.typography, '');
        }

        for (var i in css) {
            if (typeof css[i] === 'object' && 'pictures' !== i) {

                if (['hover', 'active', 'visited', 'focus'].indexOf(i) !== -1) {
                    if (css[i].typography) {
                        css.typography = css.typography || {};
                        moveTypography(css[i].typography, css.typography, i);
                        if (Object.keys(css[i].typography).length === 0) {
                            delete css[i].typography;
                        }
                    }
                    if (Object.keys(css[i]).length === 0) {
                        delete css[i];
                    }
                }

                traverseCss(css[i]);
            }
        }
    }

    function moveTypography(from, to, state) {
        moveTypographyLink('TypographyTextLink', from, to, state);
        moveTypographyLink('TypographyH1Link', from, to, state);
        moveTypographyLink('TypographyH2Link', from, to, state);
        moveTypographyLink('TypographyH3Link', from, to, state);
        moveTypographyLink('TypographyH4Link', from, to, state);
        moveTypographyLink('TypographyH5Link', from, to, state);
        moveTypographyLink('TypographyH6Link', from, to, state);
        moveTypographyLink('TypographyBulletListLink', from, to, state);
        moveTypographyLink('TypographyOrderedListLink', from, to, state);
    }

    function moveTypographyLink(type, from, to, state) {
        if (!from || !from[type] || typeof from[type] !== 'object' || !suffix[state]) return;

        var newType = type + suffix[state];

        to[newType] = to[newType] || {};
        to[newType] = from[type];

        delete from[type];
    }

    traverseCss(control.css);

    return control;
});