using System.Collections.Generic;
using UnityEngine;

namespace ThirdParty.DownloadSystem
{
    public class DownLoadHanderGroup
    {
        public ulong size;
        public long finishCount;
        public System.Action OnCallBack;
        public List<DownloadHander> DownloadHanders = new List<DownloadHander>();
        private bool _isUpdate;
        public float speed;
        private float _lasetTime;
        private float _lasetSize;
        public void AddHander(DownloadHander downloadHander)
        {
            DownloadHanders.Add(downloadHander);
        }

        public void StartUpdate()
        {
            FileDownloadSystem.Instance.AddHanderGroup(this);
            _isUpdate = true;
        }

        public void Update()
        {
            if (!_isUpdate)
            {
                return;
            }

            finishCount = 0;
            bool isOk = true;
        
            size = 0;
            for (int i = 0; i < DownloadHanders.Count; i++)
            {
                if (!DownloadHanders[i].isFinish)
                {
                    isOk = false;
                }
                else
                {
                    finishCount++;
                }

                if (DownloadHanders[i].UnityWebRequestAsyncOperation != null)
                {
                    size += DownloadHanders[i].UnityWebRequestAsyncOperation.webRequest.downloadedBytes;
                }
            }
            
            float t= Time.time - _lasetTime;
            if (t>1)
            {
              
                _lasetTime = Time.time;
               speed=  (size - _lasetSize) / (t);
               _lasetSize = size;
            }
           
           
            if (isOk)
            {
                _isUpdate = false;
                OnCallBack?.Invoke();
                FileDownloadSystem.Instance.RemoveHanderGroup(this);
            }

           
        }
    }
}