using System;
using System.Collections;

namespace TwitchInGames {
    public class Coroutine<T> : IEnumerator {
        public object Current => finalCoroutine.Current;
        public Exception Exception => exception;

        private IEnumerator originalCoroutine;
        private IEnumerator finalCoroutine;
        private Exception exception;
        private T value;

        public Coroutine(IEnumerator coroutine) {
            originalCoroutine = coroutine;
            finalCoroutine = coroutine;
        }

        public T Value {
            get {
                if(exception != null) {
                    throw exception;
                }
                return value;
            }
        }

        public bool MoveNext() {
            try {
                if(finalCoroutine.MoveNext()) {
                    return true;
                }
                for(IEnumerator enumerator; (enumerator = finalCoroutine.Current as IEnumerator) != null; finalCoroutine = enumerator) {
                    continue;
                }
                value = (T)finalCoroutine.Current;
            } catch(Exception ex) {
                exception = ex;
            }
            return false;
        }

        public void Reset() {
            originalCoroutine.Reset();
            finalCoroutine = originalCoroutine;
            exception = null;
            value = default(T);
        }
    }
}
