﻿jQuery(document).ready(function () {
    const getStyleValue = (stylesheet, selector, property) => {
        const styleRule =
            [...document.styleSheets]
                .filter(styleSheet => {
                    if (styleSheet.href && styleSheet.href.indexOf(stylesheet) > -1) {
                        return styleSheet;
                    }
                })
                .flatMap(styleSheet => {
                    return [...styleSheet.cssRules].filter(cssStyleRule => {
                        if (cssStyleRule.selectorText && cssStyleRule.selectorText === selector) {
                            return cssStyleRule;
                        }
                    });
                });

        if (styleRule[0]) {
            return styleRule[0].style.getPropertyValue(property);
        }

        return null;
    };

    const getLogoUrl = (selector) => {
        const img = document.querySelector(selector);

        if (img) {
            const style = img.currentStyle || window.getComputedStyle(img, false);
            const logo = style.backgroundImage.slice(4, -1).replace(/"/g, '');
            return logo;
        }

        return null;
    };

    window.localStorage.setItem('whitelabelSettings', JSON.stringify({
        logoUrl: getLogoUrl('img.logo'),
        primaryColor: getStyleValue('public.min.css', 'a', 'color'),
        headerBackgroundColor: getStyleValue('public.min.css', '#top-header', 'background'),
        headerLinkColor: getStyleValue('public.min.css', '.navbar-inverse .navbar-nav > li > a', 'color'),
        headerLinkHoverColor: getStyleValue('public.min.css', 'ul.nav a:hover, .navbar-nav > li > a:hover, .alt li a:active, .alt li.active', 'color'),
        favIcon: `/clientincludes/templates/${vartemplatename}/images/favicon.ico`
    }));

    // This property is used in many other pages so leaving it as a seperate property
    window.localStorage.setItem('primary-color', getStyleValue('public.min.css', 'a', 'color'));
});