using System.Collections.Generic;

namespace YooAsset
{
    public class ClearTagsCachedRawFilesOperation : AsyncOperationBase
    {
        private enum ESteps
        {
            None,
            GetCacheFiles,
            ClearCacheFiles,
            Done
        }

        private ESteps steps;
        private List<PackageBundle> cachedBundles;
        private ResourcePackage package;
        private string[] tags;
        private int clearTotalCount;

        internal ClearTagsCachedRawFilesOperation(ResourcePackage package, string[] tags)
        {
            this.package = package;
            this.tags = tags;
        }

        internal override void Start()
        {
            steps = ESteps.GetCacheFiles;
        }

        internal override void Update()
        {
            if (steps == ESteps.None || steps == ESteps.Done)
            {
                return;
            }

            if (steps == ESteps.GetCacheFiles)
            {
                var bundles = package.GetCachedTagsRawFiles(tags);
                cachedBundles = new List<PackageBundle>();
                foreach (PackageBundle b in bundles)
                {
                    if (!b.IsRawFile)
                    {
                        continue;
                    }

                    if (CacheSystem.IsCached(b.PackageName, b.CacheGUID))
                    {
                        cachedBundles.Add(b);
                    }
                }

                clearTotalCount = cachedBundles.Count;
                steps = ESteps.ClearCacheFiles;
            }

            if (steps == ESteps.ClearCacheFiles)
            {
                for (var i = cachedBundles.Count - 1; i >= 0; i--)
                {
                    var b = cachedBundles[i];
                    CacheSystem.DiscardFile(b.PackageName, b.CacheGUID);
                    cachedBundles.RemoveAt(i);
                    if (OperationSystem.IsBusy)
                    {
                        break;
                    }
                }

                if (clearTotalCount == 0)
                {
                    Progress = 1f;
                }
                else
                {
                    Progress = 1f - (1f * cachedBundles.Count / clearTotalCount);
                }

                if (cachedBundles.Count == 0)
                {
                    steps = ESteps.Done;
                    Status = EOperationStatus.Succeed;
                }
            }
        }
    }
}