/*
<copyright file="BGAssetLoaderManagerYooAssetWithAddress.cs" company="BansheeGz">
    Copyright (c) 2018-2022 All Rights Reserved
</copyright>
*/

using System;
using System.Collections.Generic;
using UnityEngine;
using YooAsset.Editor;

namespace BansheeGz.BGDatabase.Editor
{
    public class BGAssetLoaderManagerYooAssetWithAddress : BGAssetLoaderManagerYooAsset
    {
        private static readonly LocationsCacheI cache = new Cache();

        protected override LocationsCacheI MyCache => cache;

        private class Cache : LocationsCacheI
        {
            private readonly Dictionary<string, string> path2Location = new Dictionary<string, string>();
            private readonly Dictionary<string, string> location2Path = new Dictionary<string, string>();
            private bool initialized;

            public void UpdateCache()
            {
                initialized = true;
                path2Location.Clear();
                location2Path.Clear();
                List<CollectAssetInfo> assets;
                try
                {
                    assets = AssetBundleCollectorSettingData.Setting.GetAllCollectAssets(EBuildMode.SimulateBuild);
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                    return;
                }
                foreach (var asset in assets)
                {
                    try
                    {
                        path2Location.Add(asset.AssetPath, asset.Address);
                    }
                    catch (Exception e)
                    {
                        Debug.LogException(e);
                    }
                    try
                    {
                        location2Path.Add(asset.Address, asset.AssetPath);
                    }
                    catch (Exception e)
                    {
                        Debug.LogException(e);
                    }
                }

            }

            public string GetLocation(string path)
            {
                if (!initialized) UpdateCache();
                return path2Location.TryGetValue(path, out var location) ? location : null;
            }

            public string GetPath(string location)
            {
                if (!initialized) UpdateCache();
                return location2Path.TryGetValue(location, out var path) ? path : null;
            }
        }
    }
}