using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
namespace YooAsset.Editor
{
    public class BuildMapContext : IContextObject
    {
        /// 
        /// 资源包集合
        /// 
        private readonly Dictionary _bundleInfoDic = new Dictionary(10000);
        /// 
        /// 未被依赖的资源列表
        /// 
        public readonly List IndependAssets = new List(1000);
        
        /// 
        /// 参与构建的资源总数
        /// 说明:包括主动收集的资源以及其依赖的所有资源
        /// 
        public int AssetFileCount;
        /// 
        /// 资源收集命令
        /// 
        public CollectCommand Command { set; get; }
        /// 
        /// 资源包信息列表
        /// 
        public Dictionary.ValueCollection Collection
        {
            get
            {
                return _bundleInfoDic.Values;
            }
        }
        /// 
        /// 添加一个打包资源
        /// 
        public void PackAsset(BuildAssetInfo assetInfo)
        {
            string bundleName = assetInfo.BundleName;
            if (string.IsNullOrEmpty(bundleName))
                throw new Exception("Should never get here !");
            if (_bundleInfoDic.TryGetValue(bundleName, out BuildBundleInfo bundleInfo))
            {
                bundleInfo.PackAsset(assetInfo);
            }
            else
            {
                BuildBundleInfo newBundleInfo = new BuildBundleInfo(bundleName);
                newBundleInfo.PackAsset(assetInfo);
                _bundleInfoDic.Add(bundleName, newBundleInfo);
            }
        }
        /// 
        /// 是否包含资源包
        /// 
        public bool IsContainsBundle(string bundleName)
        {
            return _bundleInfoDic.ContainsKey(bundleName);
        }
        /// 
        /// 获取资源包信息,如果没找到返回NULL
        /// 
        public BuildBundleInfo GetBundleInfo(string bundleName)
        {
            if (_bundleInfoDic.TryGetValue(bundleName, out BuildBundleInfo result))
            {
                return result;
            }
            throw new Exception($"Should never get here ! Not found bundle : {bundleName}");
        }
        /// 
        /// 获取构建管线里需要的数据
        /// 
        public UnityEditor.AssetBundleBuild[] GetPipelineBuilds()
        {
            List builds = new List(_bundleInfoDic.Count);
            foreach (var bundleInfo in _bundleInfoDic.Values)
            {
                builds.Add(bundleInfo.CreatePipelineBuild());
            }
            return builds.ToArray();
        }
        /// 
        /// 创建着色器信息类
        /// 
        public void CreateShadersBundleInfo(string shadersBundleName)
        {
            if (IsContainsBundle(shadersBundleName) == false)
            {
                var shaderBundleInfo = new BuildBundleInfo(shadersBundleName);
                _bundleInfoDic.Add(shadersBundleName, shaderBundleInfo);
            }
        }
    }
}