<?php

namespace KupShop\CheckAppBundle\Admin\Util;

use KupShop\KupShopBundle\Util\StringUtil;

class AssetsLoader
{
    public static function getAssets()
    {
        if (getVal('dev')) {
            $assets = json_decode(self::getContentsCurl('https://www.kupshop.local:3000/web/bundles/warehouse/check-app/asset-manifest.json'), true);

            $assets = array_map(function ($val) {
                return 'https://www.kupshop.local:3000/web/bundles/warehouse/check-app/'.$val;
            }, $assets['entrypoints'] ?? $assets);
        } else {
            $assets = json_decode(file_get_contents('./web/bundles/warehouse/check-app/asset-manifest.json'), true);
            if (!empty($assets['entrypoints'])) {
                $assets = $assets['entrypoints'];
            }

            $assets = array_map(function ($path) {return "/web/bundles/warehouse/check-app/{$path}"; }, $assets ?? []);
        }

        return ['js' => array_filter($assets, function ($x) {return StringUtil::endsWith($x, '.js'); }),
            'css' => array_filter($assets, function ($x) {return StringUtil::endsWith($x, '.css'); }), ];
    }

    protected static function getContentsCurl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }
}
