using XGame.Editor.Asset;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using XGame.Framework.Asset;

namespace XGame.Editor.Build.AssetBundles
{
    internal class AssetBundleBuildTask
    {
        private BundleContext _context;
        private BundleManifestsController _manifestsController;
        private IBuildPipeline _buildPipeline;

        public AssetBundleBuildTask(BundleContext context, BundleManifestsController manifestsController, IBuildPipeline buildPipeline)
        {
            _context = context;
            _manifestsController = manifestsController;
            _buildPipeline = buildPipeline;
        }

        public bool Run()
        {
            List<AssetBundleData> bundleBuilds = null;
            try
            {
                if (!_manifestsController.GenerateManifests())
                {
                    return false;
                }
                bundleBuilds = _context.BundleDataLst;
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                return false;
            }

            //Debug.Log($"ManifestBundleId: {build.TestBundleId()}");
            bundleBuilds.Add(CreateManifestBundle());
            return _buildPipeline.BuildAssetBundles(ConverToUniBundleBuilds(bundleBuilds));
        }
        private AssetBundleData CreateManifestBundle()
        {
            var assetNames = new List<string>() { PathDefine.BundleManifestPath, PathDefine.SceneAssetBundleManifestPath, PathDefine.ReferenceManifestPath, PathDefine.ProductAssetManifestPath };
            var addressableNames = new List<string>() { Define.ASSET_BUNDLE_MANIFEST, Define.SCENE_BUNDLE_MANIFEST, Define.ASSET_REFERENCE_MANIFEST, Define.PRODUCT_ASSET_MANIFEST };
            if (System.IO.File.Exists(PathDefine.BuiltInAssetManifestPath))
            {
                assetNames.Add(PathDefine.BuiltInAssetManifestPath);
                addressableNames.Add(Define.BUILTIN_ASSET_MANIFEST);
            }
            var build = new AssetBundleData()
            {
                assetBundleName = Define.MANIFEST_BUNDLE_NAME,
                assetBundleVariant = Define.BUNDLE_VARIANT,
                originBundleName = Define.MANIFEST_BUNDLE_NAME,
                assetNames = assetNames.ToArray(),
                addressableNames = addressableNames.ToArray()
            };
            return build;
        }
        private UnityEditor.AssetBundleBuild[] ConverToUniBundleBuilds(List<AssetBundleData> bundleBuilds)
        {
            var count = bundleBuilds.Count;
            var uniBuilds = new UnityEditor.AssetBundleBuild[count];
            for (var i = 0; i < count; i++)
            {
                uniBuilds[i] = bundleBuilds[i].ToUniBuild();
            }
            return uniBuilds;
        }
    }
}
