using UnityEngine;
using System.Collections;
using System;

namespace Me.StefS.UnityUtility {
    public static class Corutines {
        public static IEnumerator WaitForUnscaledSeconds(float seconds) {
            float aggregated = 0;
            while (aggregated < seconds) {
                aggregated += Time.unscaledDeltaTime;
                yield return null;
            }
        }

        public static IEnumerator Wait() {
            while (true) {
                yield return null;
            }
        }

        public static IEnumerator WaitForSeconds(float seconds) {
            float aggregated = 0;
            while (aggregated < seconds) {
                aggregated += Time.deltaTime;
                yield return null;
            }
        }

        public static IEnumerator Execute(Action action) {
            action();
            yield return null;
        }

        public static IEnumerator While(Func<bool> check, IEnumerator nestedCorutine) {
            while (check.Invoke() && nestedCorutine.MoveNext()) {
                yield return nestedCorutine.Current;
            }
        }

        public static IEnumerator Then(this IEnumerator first, IEnumerator after) {
            while (first.MoveNext()) {
                yield return first.Current;
            }

            yield return after;
        }

        public static IEnumerator InParallel(this IEnumerator origin, IEnumerator parallel) {
            bool originNext = true;
            bool parallelNext = true;
            while (originNext || parallelNext) {
                originNext = origin.MoveNext();
                parallelNext = parallel.MoveNext();
                yield return originNext ? origin.Current : parallel.Current;
            }
        }

        public static IEnumerator Alternating(this IEnumerator origin, IEnumerator parallel) {
            bool originNext = true;
            bool parallelNext = true;
            bool isFirst = true;
            while (originNext || parallelNext) {
                if (isFirst) {
                    originNext = origin.MoveNext();
                    if (originNext) {
                        yield return origin.Current;
                    }
                    else {
                        parallelNext = parallel.MoveNext();
                        if (parallelNext) {
                            yield return parallel.Current;
                        }
                    }
                }
                else {
                    parallelNext = parallel.MoveNext();
                    if (parallelNext) {
                        yield return parallel.Current;
                    }
                    else {
                        originNext = origin.MoveNext();
                        if (originNext) {
                            yield return origin.Current;
                        }
                    }
                }

                isFirst = !isFirst;
            }
        }
    }
}