using System;
using System.Collections.Generic;
using UnityEngine;

namespace Jovian.Utilities
{
    public interface ILoadingProcess {
        bool HasLoaded { get; }
    }
    
    public class LoadingProcessHandler {
        private readonly HashSet<ILoadingProcess> allProcesses = new();
        private readonly HashSet<ILoadingProcess> anyProcesses = new();

        public event Action OnLoadComplete;

        public bool IsLoadingComplete() {
            foreach(ILoadingProcess loadingProcess in anyProcesses) {
                if(loadingProcess.HasLoaded) {
                    return true;
                }
            }
            bool areAllProcessesComplete = true;
            foreach(ILoadingProcess loadingProcess in allProcesses) {
                if(loadingProcess.HasLoaded == false) {
                    areAllProcessesComplete = false;
                    break;
                }
            }
            return areAllProcessesComplete;
        }

        public void AddAllProcess(ILoadingProcess loadingProcess) {
            allProcesses.Add(loadingProcess);
        }

        public void AddAnyProcess(ILoadingProcess loadingProcess) {
            anyProcesses.Add(loadingProcess);
        }

        public void Complete() {
            OnLoadComplete?.Invoke();
        }
    }

    public class TimeElapsedLoadingProcess : ILoadingProcess {
        private readonly float endTime;
        public bool HasLoaded => Time.realtimeSinceStartup > endTime;
        public TimeElapsedLoadingProcess(float duration) {
            endTime = Time.realtimeSinceStartup + duration;
        }
    }
}
