using System;
using BrewMonster;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.ResourceLocations;
namespace BrewMonster.Scripts
{
///
/// Runtime rewrite of bundle/catalog URLs via
/// (e.g. swap CDN host or path prefix). Must run before the first successful remote load — ideally before
/// if all remote ids should be rewritten.
///
public static class AddressablesRuntimeUrlRewriter
{
static Func s_previousTransform;
static string s_fromPrefix;
static string s_toPrefix;
///
/// When true, the installed rewriter calls the previous first.
///
public static bool ChainPreviousTransform { get; set; } = true;
///
/// Replaces the start of each location’s when it begins with
/// (e.g. build-time profile URL) by (runtime CDN).
///
public static void InstallPrefixRewrite(string fromPrefix, string toPrefix)
{
if (string.IsNullOrEmpty(fromPrefix))
{
BMLogger.LogError("AddressablesRuntimeUrlRewriter: fromPrefix is null or empty.");
return;
}
s_fromPrefix = fromPrefix;
s_toPrefix = toPrefix ?? string.Empty;
if (ChainPreviousTransform)
s_previousTransform = Addressables.InternalIdTransformFunc;
Addressables.InternalIdTransformFunc = Transform;
BMLogger.Log($"AddressablesRuntimeUrlRewriter: Installed prefix rewrite (from length={fromPrefix.Length}, to length={s_toPrefix.Length}).");
}
///
/// Removes this package’s rewrite and restores the delegate that was present at install time (if any).
///
public static void ClearInstalledRewrite()
{
if (Addressables.InternalIdTransformFunc == Transform)
{
Addressables.InternalIdTransformFunc = s_previousTransform;
s_previousTransform = null;
s_fromPrefix = null;
s_toPrefix = null;
BMLogger.Log("AddressablesRuntimeUrlRewriter: Cleared installed rewrite.");
}
}
static string Transform(IResourceLocation location)
{
string id = location != null ? location.InternalId : null;
if (string.IsNullOrEmpty(id))
return id;
if (ChainPreviousTransform && s_previousTransform != null)
id = s_previousTransform(location);
if (!string.IsNullOrEmpty(s_fromPrefix) &&
id.StartsWith(s_fromPrefix, StringComparison.OrdinalIgnoreCase))
{
return s_toPrefix + id.Substring(s_fromPrefix.Length);
}
return id;
}
}
}