using System;

namespace XGame.Framework.Asyncs
{
    public abstract class Async : IAsync
    {
        private AsyncListenerOperation _operation;
        public object State { get; set; }
        public Exception Exception { get; set; }
        public bool IsCompleted { get; protected set; }

        public virtual float Progress { get; protected set; }

        public Async()
        {
            Progress = 0;
            _operation = new AsyncListenerOperation();
        }

        public virtual void Completed()
        {
            if (IsCompleted)
            {
                Log.Warn("Connot Completed Again!!");
                return;
            }

            IsCompleted = true;
            Progress = 1.0f;
            _operation.OnCompleted(this);
        }

        public IAsync On(OnAsyncCompleted action)
        {
            if (action != null)
            {
                if (IsCompleted)
                {
                    action.SaveInvoke(this);
                }
                else
                {
                    _operation.On(action);
                }
            }
            return this;
        }

        public IAsync On(IAsyncListener listener, int order = 0)
        {
            if (listener == null) return this;
            if (IsCompleted)
            {
                listener.SaveInvoke(this);
                return this;
            }
            _operation.On(listener, order);
            return this;
        }

        public IAsync RemoveOn(OnAsyncCompleted action)
        {
            _operation.RemoveOn(action);
            return this;
        }

        public IAsync RemoveOn(IAsyncListener listener)
        {
            _operation.RemoveOn(listener);
            return this;
        }

        public IAsync RemoveAll()
        {
            OnRemoveAll();
            _operation.Clear();
            return this;
        }

        protected virtual void OnRemoveAll()
        {

        }
    }
}