<?php
namespace WpAssetCleanUpPro\OptimiseAssets;

use WpAssetCleanUp\Main;
use WpAssetCleanUp\Misc;
use WpAssetCleanUp\ObjectCache;
use WpAssetCleanUp\OptimiseAssets\OptimizeCommon;

use WpAssetCleanUpPro\MainPro;

/**
 * Class MatchMediaLoadPro
 * @package WpAssetCleanUp\OptimiseAssets
 */
class MatchMediaLoadPro
{
    /**
     * @param $htmlSource string
     * @param $matchesSourcesFromTags array
     * @param string
     *
     * @return string|string[]
     */
    public static function alterHtmlSourceForMediaQueriesLoad($htmlSource, $matchesSourcesFromTags, $assetType)
    {
        if ($assetType === 'styles') {
            $linkTagsToFallback = array();
        }

        if (! empty($matchesSourcesFromTags)) {
            foreach ($matchesSourcesFromTags as $matchedValues) {
                $matchedTag = $matchedValues[0];

                if ($assetType === 'scripts') {
                    $maybeSrcValue = Misc::getValueFromTag($matchedTag, 'src', 'dom_with_fallback');

                    if ( ! $maybeSrcValue) {
                        // The RegEx fetched the first part of the inline tag starting with <script
                        // Get the rest of the content including the closing </script>
                        $matchedTagResult = self::extractFullScriptTagFromOpenTag($htmlSource, $matchedTag);
                        $matchedTag       = $matchedTagResult['full_tag'];

                        }
                }

                $newTag = self::maybeAlterToMatchMediaTag($matchedTag, $assetType);

                if ($matchedTag !== $newTag) {
                    $htmlSource = str_replace($matchedTag, $newTag, $htmlSource);

                    if ($assetType === 'styles') {
                        // Use the <NOSCRIPT> tags as a fallback for LINK tags in case JavaScript is disabled in the visitor's browser
                        // There's no point in adding any for the SCRIPT tags as they will not load at all anyway
                        $newFallbackTag = str_replace('data-wpacu-apply-media-query=', 'data-wpacu-applied-media-query=', $matchedTag);
                        $linkTagsToFallback[] = $newFallbackTag;
                    }
                }
            }
        }

        if ( ! empty($linkTagsToFallback) ) {
            ObjectCache::wpacu_cache_add('wpacu_link_tags_fallback', $linkTagsToFallback);
        }

        return $htmlSource;
    }

    /**
     * @param $matchedTag
     * @param $assetType
     *
     * @return mixed|string|void
     */
    public static function maybeAlterToMatchMediaTag($matchedTag, $assetType)
    {
        // Check if the tag has any 'data-wpacu-skip' attribute; if it does, do not alter it
        if (Misc::hasExactDataAttr($matchedTag, 'data-wpacu-skip')) {
            return $matchedTag;
        }

        if ($assetType === 'styles') {
            preg_match_all('#data-wpacu-style-handle=(["\'])' . '(.*)' . '(["\'])#Usmi', $matchedTag, $outputMatchesMedia);
            $tagHandle = isset($outputMatchesMedia[2][0]) ? trim($outputMatchesMedia[2][0], '"\'') : '';

            // [START] Check if Handle is Eligible For The Feature
            // The handle has to be a "child" or "independent", but not a "parent"
            $allCssDepsParentToChild = self::getAllParentToChildInRelationToMarkedHandles($assetType);
            // [END] Check if Handle is Eligible For The Feature

            if (isset($allCssDepsParentToChild[$tagHandle])) {
                // Has "children", this is not supported yet, and somehow it was added as a rule (or someone tries to hack it)
                return $matchedTag;
            }

            preg_match_all('#data-wpacu-apply-media-query=(["\'])' . '(.*)' . '(["\'])#Usmi', $matchedTag, $outputMatchesMedia);
            $mediaQueryValue = isset($outputMatchesMedia[2][0]) ? trim($outputMatchesMedia[2][0], '"\'') : '';

            }

        if ($assetType === 'scripts') {
            // [START] Check if Handle is Eligible For The Feature
            // The handle has to be a "child" or "independent", but not a "parent"
            $allJsDepsParentToChild = self::getAllParentToChildInRelationToMarkedHandles($assetType);
            // [END] Check if Handle is Eligible For The Feature

            preg_match_all('#data-wpacu-script-handle=(["\'])' . '(.*)' . '(["\'])#Usmi', $matchedTag, $outputMatchesMedia);
            $tagHandle = isset($outputMatchesMedia[2][0]) ? trim($outputMatchesMedia[2][0], '"\'') : '';

            if (isset($allJsDepsParentToChild[$tagHandle])) {
                // Has "children", this is not supported yet, and somehow it was added as a rule (or someone tries to hack it)
                return $matchedTag;
            }

            preg_match_all('#data-wpacu-apply-media-query=(["\'])' . '(.*)' . '(["\'])#Usmi', $matchedTag, $outputMatchesMedia);
            $mediaQueryValue = isset($outputMatchesMedia[2][0]) ? trim($outputMatchesMedia[2][0], '"\'') : '';
        }

        return self::applyChangesToMatchMediaTag($tagHandle, $matchedTag, $mediaQueryValue, $assetType);
    }

    /**
     * @param $tagHandle
     * @param $htmlTag
     * @param $mediaQueryValue
     * @param $assetType
     *
     * @return string
     */
    public static function applyChangesToMatchMediaTag($tagHandle, $htmlTag, $mediaQueryValue, $assetType)
    {
        if ( ( ! $tagHandle ) || ( ! $htmlTag ) || ( ! $mediaQueryValue ) ) {
            return $htmlTag;
        }

        // Extra check: make sure the targeted handle doesn't have any "children" (independent or has "parents")
        // as there's no support for such handles at this time

        // Check if there are any media queries set (e.g. mobile, desktop, custom ones) for this tag
        // To only load when the media query matches
        if ($assetType === 'styles') {
            $attrToSet = 'wpacu-' . str_replace(array(' '), '_', sanitize_title( $tagHandle ) . '-href');
            $htmlTag   = str_replace( ' href=', ' ' . $attrToSet . '=', $htmlTag );

            return str_replace('data-wpacu-apply-media-query=', 'data-wpacu-applied-media-query=', $htmlTag);
        }

        if ($assetType === 'scripts') {
            $maybeSrcValue = Misc::getValueFromTag($htmlTag, 'src', 'dom_with_fallback');

            if ($maybeSrcValue) {
                $attrToSet = 'wpacu-' . str_replace(array(' '), '_', sanitize_title($tagHandle) . '-src');
                $htmlTag   = str_replace(' src=', ' ' . $attrToSet . '=', $htmlTag);
            } else {
                // No "src"? It will be a script tag opener (inline) like: <script type="text/javascript" ... >
                $htmlTag = self::wrapInlineScriptContentForLaterCalling($htmlTag);

                }

            return str_replace('data-wpacu-apply-media-query=', 'data-wpacu-applied-media-query=', $htmlTag);
        }

        // Finally, return the tag if there were no changes applied
        return $htmlTag;
    }

    /**
     * @param $htmlTag
     *
     * @return string
     */
    public static function wrapInlineScriptContentForLaterCalling($htmlTag)
    {
        $htmlTag = trim($htmlTag);

        // Make sure it's a <script> tag
        if (stripos($htmlTag, '<script') !== 0) {
            return $htmlTag;
        }

        // Find the end of the opening tag
        $openTagEndPos = strpos($htmlTag, '>');
        if ($openTagEndPos === false) {
            return $htmlTag;
        }

        $openTag = substr($htmlTag, 0, $openTagEndPos + 1); // Includes ">"
        $remaining = substr($htmlTag, $openTagEndPos + 1);

        $len = strlen($remaining);
        $inSingle = false;
        $inDouble = false;
        $escaped = false;

        for ($i = 0; $i < $len - 8; $i++) {
            $char = $remaining[$i];

            if ($escaped) {
                $escaped = false;
                continue;
            }

            if ($char === '\\') {
                $escaped = true;
                continue;
            }

            if ( ! $inDouble && $char === "'" ) {
                $inSingle = !$inSingle;
                continue;
            }

            if ( ! $inSingle && $char === '"' ) {
                $inDouble = !$inDouble;
                continue;
            }

            // If we found the real closing </script>
            if ( ! $inSingle && ! $inDouble && stripos(substr($remaining, $i, 9), '</script>') === 0 ) {
                $scriptContent = substr($remaining, 0, $i);

                $uniqueId = Misc::getValueFromTag($htmlTag, 'id', 'dom_with_fallback');

                $uniqueVarName = 'wpacuInlineCode_' . preg_replace('/[^a-zA-Z0-9_$]/', '_', $uniqueId);

                $wrappedContent = 'var ' . $uniqueVarName . ' = ' . json_encode(trim($scriptContent)) . ';';

                return $openTag . $wrappedContent . '</script>';
            }
        }

        // If we never found the proper closing tag, return the original
        return $htmlTag;
    }

    /**
     * @param $htmlSource
     * @param $scriptOpenTag
     *
     * @return array|false
     */
    public static function extractFullScriptTagFromOpenTag($htmlSource, $scriptOpenTag)
    {
        $scriptOpenTag = trim($scriptOpenTag);
        $openPos = strpos($htmlSource, $scriptOpenTag);

        if ($openPos === false) {
            return false;
        }

        $innerStart = $openPos + strlen($scriptOpenTag);

        $len = strlen($htmlSource);

        $inSingle = false;
        $inDouble = false;
        $escaped = false;

        for ($i = $innerStart; $i < $len - 8; $i++) {
            $char = $htmlSource[$i];

            if ($escaped) {
                $escaped = false;
                continue;
            }

            if ($char === '\\') {
                $escaped = true;
                continue;
            }

            if (!$inDouble && $char === "'") {
                $inSingle = !$inSingle;
                continue;
            }

            if (!$inSingle && $char === '"') {
                $inDouble = !$inDouble;
                continue;
            }

            if ( ! $inSingle && ! $inDouble && stripos(substr($htmlSource, $i, 9), '</script>') === 0 ) {
                $scriptClosePos = $i;
                $fullTagLength  = $scriptClosePos + 9 - $openPos;
                $fullTag        = substr($htmlSource, $openPos, $fullTagLength);
                $scriptContent  = substr($htmlSource, $innerStart, $scriptClosePos - $innerStart);

                return array(
                    'full_tag'        => $fullTag,
                    'open_tag'        => $scriptOpenTag,
                    'script_content'  => $scriptContent,
                    'start_pos'       => $openPos,
                    'end_pos'         => $scriptClosePos + 9
                );
            }
        }

        return false;
    }

    /**
     * This is the JS script that will scan all LINK and SCRIPT tags that should load based on the media query
     */
    public static function setConditionalLoadingScripts()
    {
        if (defined('WPACU_NO_MEDIA_QUERIES_LOAD_RULES_SET_FOR_ASSETS')) {
            return;
        }

        add_action('wp_footer', static function () {
            if (OptimizeCommon::preventAnyFrontendOptimization() || Main::instance()->preventAssetsSettings()) {
                return;
            }

            $mediaQueriesLoadOnlyValid = MainPro::getMediaQueriesLoad('only_valid');

            if ( empty($mediaQueriesLoadOnlyValid['styles']) && empty($mediaQueriesLoadOnlyValid['scripts']) ) {
                return;
            }

            $hasCondStyles  = ! empty($mediaQueriesLoadOnlyValid['styles']);
            $hasCondScripts = ! empty($mediaQueriesLoadOnlyValid['scripts']);

            self::printConditionalLoadJsScript($hasCondStyles, $hasCondScripts);
        });
    }

    /**
     * @param $hasCondStyles
     * @param $hasCondScripts
     *
     * @return void
     */
    public static function printConditionalLoadJsScript($hasCondStyles, $hasCondScripts)
    {
        ?>
            <script <?php echo Misc::getScriptTypeAttribute(); ?> data-wpacu-own-inline-script="true">
                window.wpacuPlugin = window.wpacuPlugin || {};
                var wpacuMediaQueryAttr = 'data-wpacu-applied-media-query';
            <?php
            if ( $hasCondStyles ) {
                if ( (defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG) || isset($_GET['wpacu_debug']) ) {
                ?>
                    wpacuPlugin.initConditionalStyles = function () {
                        var stylePlaceholders = document.querySelectorAll('link['+ wpacuMediaQueryAttr +']');

                        stylePlaceholders.forEach(function (el) {
                            var media = el.getAttribute(wpacuMediaQueryAttr);
                            if ( ! media ) return;

                            // Look for custom wpacu-*-href attribute holding the real href
                            var attrName = Array.from(el.attributes).find(function (attr) {
                                return /^wpacu-.*-href$/.test(attr.name);
                            });

                            if ( ! attrName) return;

                            var href = attrName.value;
                            if ( ! href ) return;

                            var alreadyLoaded = false;

                            function loadStyleIfMatch(e) {
                                if ((e && e.matches) || (typeof e === 'boolean' && e)) {
                                    if ( ! alreadyLoaded ) {
                                        alreadyLoaded = true;

                                        var link = document.createElement('link');

                                        link.rel   = 'stylesheet';
                                        link.href  = href;
                                        link.media = 'all'; // Let it apply immediately

                                        document.head.appendChild(link);
                                    }
                                }
                            }

                            try {
                                var mq = window.matchMedia(media);
                                loadStyleIfMatch(mq);

                                if (typeof mq.addEventListener === 'function') {
                                    mq.addEventListener('change', loadStyleIfMatch);
                                } else if (typeof mq.addListener === 'function') {
                                    mq.addListener(loadStyleIfMatch);
                                }
                            } catch (e) {
                                loadStyleIfMatch(true);
                            }
                        });
                    };

                    // Auto-run when DOM is ready
                    if (document.readyState === 'loading') {
                        document.addEventListener('DOMContentLoaded', wpacuPlugin.initConditionalStyles);
                    } else {
                        wpacuPlugin.initConditionalStyles();
                    }
                <?php
                } else {
                ?>
                    wpacuPlugin.initConditionalStyles=function(){var stylePlaceholders=document.querySelectorAll('link['+wpacuMediaQueryAttr+']');stylePlaceholders.forEach(function(el){var media=el.getAttribute(wpacuMediaQueryAttr);if(!media)return;var attrName=Array.from(el.attributes).find(function(attr){return/^wpacu-.*-href$/.test(attr.name)});if(!attrName)return;var href=attrName.value;if(!href)return;var alreadyLoaded=!1;function loadStyleIfMatch(e){if((e&&e.matches)||(typeof e==='boolean'&&e)){if(!alreadyLoaded){alreadyLoaded=!0;var link=document.createElement('link');link.rel='stylesheet';link.href=href;link.media='all';document.head.appendChild(link)}}}
                        try{var mq=window.matchMedia(media);loadStyleIfMatch(mq);if(typeof mq.addEventListener==='function'){mq.addEventListener('change',loadStyleIfMatch)}else if(typeof mq.addListener==='function'){mq.addListener(loadStyleIfMatch)}}catch(e){loadStyleIfMatch(!0)}})};if(document.readyState==='loading'){document.addEventListener('DOMContentLoaded',wpacuPlugin.initConditionalStyles)}else{wpacuPlugin.initConditionalStyles()}
                <?php
                }
            }

            if ( $hasCondScripts ) {
                if ( (defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG) || isset($_GET['wpacu_debug']) ) {
                ?>
                    /**
                     * Executes JS code with retries until no error
                     */
                    wpacuPlugin.tryUntilNoError = function (codeString, options) {
                        options = options || {};

                        var waited   = 0;
                        var interval = options.checkInterval || 50;
                        var timeout  = options.timeout || 5000;

                        function tryRun() {
                            try {
                                new Function(codeString)();
                            } catch (e) {
                                waited += interval;

                                if (waited < timeout) {
                                    setTimeout(tryRun, interval);
                                } else {
                                    console.warn('[Asset CleanUp] Script failed after ' + timeout + 'ms.', e);
                                }
                            }
                        }

                        if (document.readyState === 'loading') {
                            document.addEventListener('DOMContentLoaded', tryRun);
                        } else {
                            tryRun();
                        }
                    };

                    /**
                     * Loads deferred scripts and runs their inline "after" if the media query matches
                     */
                    wpacuPlugin.initConditionalScripts = function () {
                        var scriptPlaceholders = document.querySelectorAll('script['+ wpacuMediaQueryAttr +'][id]');

                        for (var i = 0; i < scriptPlaceholders.length; i++) {
                            (function () {
                                var scriptTag = scriptPlaceholders[i];
                                var media = scriptTag.getAttribute(wpacuMediaQueryAttr);
                                if ( ! media ) return;

                                var attrs   = scriptTag.attributes;
                                var srcAttr = null;

                                for (var j = 0; j < attrs.length; j++) {
                                    var attrName = attrs[j].name;
                                    if (attrName.indexOf('-src') !== -1 && attrName.indexOf('wpacu-') === 0) {
                                        srcAttr = attrName;
                                        break;
                                    }
                                }

                                if (srcAttr) {
                                    var realSrc = scriptTag.getAttribute(srcAttr);
                                    if ( ! realSrc ) return;

                                    var alreadyLoaded = false;

                                    function loadScriptIfMatch(e) {
                                        if ((e && e.matches) || (typeof e === 'boolean' && e)) {
                                            if ( ! alreadyLoaded ) {
                                                alreadyLoaded = true;

                                                var newScript   = document.createElement('script');
                                                newScript.src   = realSrc;
                                                newScript.defer = false;

                                                var afterScriptId = scriptTag.id + '-after';
                                                var afterScript = document.getElementById(afterScriptId);
                                                if (afterScript) {
                                                    var inlineJs = afterScript.textContent || afterScript.innerText || '';
                                                    afterScript.parentNode.removeChild(afterScript);

                                                    // Attempt to extract the variable name if declared like "var uniqueVar = '...';"
                                                    var varNameMatch = inlineJs.match(/var\s+(wpacuInlineCode_[a-zA-Z0-9_$]+)\s*=\s*(["'`])/);
                                                    //console.log(varNameMatch);

                                                    newScript.onload = (function (code) {
                                                        return function () {
                                                            if (typeof wpacuPlugin !== 'undefined' && typeof wpacuPlugin.tryUntilNoError === 'function') {

                                                                if (varNameMatch && typeof window[varNameMatch[1]] !== 'undefined') {
                                                                    wpacuPlugin.tryUntilNoError(window[varNameMatch[1]]);
                                                                } else {
                                                                    wpacuPlugin.tryUntilNoError(code);
                                                                }
                                                            } else {
                                                                try { new Function(code)(); } catch (e) {}
                                                            }
                                                        };
                                                    })(inlineJs);
                                                }

                                                scriptTag.parentNode.replaceChild(newScript, scriptTag);
                                            }
                                        }
                                    }

                                    try {
                                        var mq = window.matchMedia(media);
                                        loadScriptIfMatch(mq);

                                        if (typeof mq.addEventListener === 'function') {
                                            mq.addEventListener('change', loadScriptIfMatch);
                                        } else if (typeof mq.addListener === 'function') {
                                            mq.addListener(loadScriptIfMatch);
                                        }
                                    } catch (e) {
                                        loadScriptIfMatch(true);
                                    }
                                }
                            })();
                        }
                    };

                    // Run once DOM is ready
                    if (document.readyState === 'loading') {
                        document.addEventListener('DOMContentLoaded', wpacuPlugin.initConditionalScripts);
                    } else {
                        wpacuPlugin.initConditionalScripts();
                    }
                <?php
                } else {
                ?>
                    wpacuPlugin.tryUntilNoError=function(codeString,options){options=options||{};var waited=0;var interval=options.checkInterval||50;var timeout=options.timeout||5000;function tryRun(){try{new Function(codeString)()}catch(e){waited+=interval;if(waited<timeout){setTimeout(tryRun,interval)}else{console.warn('[Asset CleanUp] Script failed after '+timeout+'ms.',e)}}}
                        if(document.readyState==='loading'){document.addEventListener('DOMContentLoaded',tryRun)}else{tryRun()}};wpacuPlugin.initConditionalScripts=function(){var scriptPlaceholders=document.querySelectorAll('script['+wpacuMediaQueryAttr+'][id]');for(var i=0;i<scriptPlaceholders.length;i++){(function(){var scriptTag=scriptPlaceholders[i];var media=scriptTag.getAttribute(wpacuMediaQueryAttr);if(!media)return;var attrs=scriptTag.attributes;var srcAttr=null;for(var j=0;j<attrs.length;j++){var attrName=attrs[j].name;if(attrName.indexOf('-src')!==-1&&attrName.indexOf('wpacu-')===0){srcAttr=attrName;break}}
                        if(srcAttr){var realSrc=scriptTag.getAttribute(srcAttr);if(!realSrc)return;var alreadyLoaded=!1;function loadScriptIfMatch(e){if((e&&e.matches)||(typeof e==='boolean'&&e)){if(!alreadyLoaded){alreadyLoaded=!0;var newScript=document.createElement('script');newScript.src=realSrc;newScript.defer=!1;var afterScriptId=scriptTag.id+'-after';var afterScript=document.getElementById(afterScriptId);if(afterScript){var inlineJs=afterScript.textContent||afterScript.innerText||'';afterScript.parentNode.removeChild(afterScript);var varNameMatch=inlineJs.match(/var\s+(wpacuInlineCode_[a-zA-Z0-9_$]+)\s*=\s*(["'`])/);newScript.onload=(function(code){return function(){if(typeof wpacuPlugin!=='undefined'&&typeof wpacuPlugin.tryUntilNoError==='function'){if(varNameMatch&&typeof window[varNameMatch[1]]!=='undefined'){wpacuPlugin.tryUntilNoError(window[varNameMatch[1]])}else{wpacuPlugin.tryUntilNoError(code)}}else{try{new Function(code)()}catch(e){}}}})(inlineJs)}
                            scriptTag.parentNode.replaceChild(newScript,scriptTag)}}}
                            try{var mq=window.matchMedia(media);loadScriptIfMatch(mq);if(typeof mq.addEventListener==='function'){mq.addEventListener('change',loadScriptIfMatch)}else if(typeof mq.addListener==='function'){mq.addListener(loadScriptIfMatch)}}catch(e){loadScriptIfMatch(!0)}}})()}};if(document.readyState==='loading'){document.addEventListener('DOMContentLoaded',wpacuPlugin.initConditionalScripts)}else{wpacuPlugin.initConditionalScripts()}
                <?php
                }
            }
            ?>
            </script>
        <?php
    }

	/**
	 * If any current handle marked for media query load has any "children", do not alter it
	 *
	 * @param $assetType
	 *
	 * @return array
	 */
	public static function getAllParentToChildInRelationToMarkedHandles($assetType)
	{
        if ($allCssDepsParentToChild = ObjectCache::wpacu_cache_get( 'wpacu_get_deps_parent_to_child_'.$assetType)) {
            return $allCssDepsParentToChild;
        }

		if ($assetType === 'styles') {
			$allCssDepsParentToChild = array();
			$allCssMediaQueriesLoadMarkedHandlesList = ObjectCache::wpacu_cache_get('wpacu_css_media_queries_load_current_page') ?: array();

			global $wp_styles;

			if ( ! empty($wp_styles->registered) ) {
				foreach ( $wp_styles->registered as $assetHandle => $assetObj ) {
					if ( ! empty( $assetObj->deps ) ) {
						foreach ( $assetObj->deps as $dep ) {
							if (isset($wp_styles->done) && in_array($assetHandle, $allCssMediaQueriesLoadMarkedHandlesList) && in_array($assetHandle, $wp_styles->done)) {
								$allCssDepsParentToChild[$dep][] = $assetHandle;
							}
						}
					}
				}
			}

            ObjectCache::wpacu_cache_set( 'wpacu_get_deps_parent_to_child_'.$assetType, $allCssDepsParentToChild );
			return $allCssDepsParentToChild;
		}

		if ($assetType === 'scripts') {
			$allJsDepsParentToChild = array();
			$allJsMediaQueriesLoadMarkedHandlesList = ObjectCache::wpacu_cache_get( 'wpacu_js_media_queries_load_current_page' ) ?: array();

			global $wp_scripts;

			if ( ! empty( $wp_scripts->registered ) ) {
				foreach ( $wp_scripts->registered as $assetHandle => $assetObj ) {
					if ( ! empty( $assetObj->deps ) ) {
						foreach ( $assetObj->deps as $dep ) {
							if ( isset( $wp_scripts->done ) && is_array($wp_scripts->done) && is_array($allJsMediaQueriesLoadMarkedHandlesList) &&
							     in_array($assetHandle, $allJsMediaQueriesLoadMarkedHandlesList) &&
							     in_array($assetHandle, $wp_scripts->done) ) {
								$allJsDepsParentToChild[ $dep ][] = $assetHandle;
							}
						}
					}
				}
			}

            ObjectCache::wpacu_cache_set( 'wpacu_get_deps_parent_to_child_'.$assetType, $allCssDepsParentToChild );
			return $allJsDepsParentToChild;
		}

		return array(); // should get here, unless the $assetType is not valid
	}
}
