﻿/*
	The MIT License

	Copyright (c) 2022 Park Hyun-Kyu

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

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

public class MonoBehaviourEx : MonoBehaviour
{
    public AnimationCurve defaultCurve = AnimationCurve.Linear(0f, 0f, 1f, 1f);
    protected Hashtable coTable = new Hashtable();

    public class CoroutineDummy : MonoBehaviour
    {
        public void RunCoroutine(IEnumerator _action)
        {
            StartCoroutine(RunCoroutineNext(_action));
        }
        IEnumerator RunCoroutineNext(IEnumerator _action)
        {
            yield return StartCoroutine(_action);
            DestroyImmediate(gameObject);
        }
    }


    public void StartCoroutineEx( IEnumerator _action )
    {
        GameObject coObject = new GameObject("Coroutine Dummy");
        coObject.hideFlags = HideFlags.HideInHierarchy;
        coObject.AddComponent<CoroutineDummy>().RunCoroutine(_action);
    }

    protected void StopAnimate(string _key)
    {
        if(coTable[_key] != null)
        {
            StopCoroutine((Coroutine)coTable[_key]);
        }    
    }
    
    protected void StopAllAnimate()
    {
        foreach (DictionaryEntry de in coTable)
        {
            StopCoroutine((Coroutine)de.Value);
        }
        coTable.Clear();
    }

    protected Chaine DelayAction(string _key, float _delay, System.Action _action)
    {
        Chaine chine = new Chaine();
        if (coTable[_key] != null)
        {
            StopCoroutine((Coroutine)coTable[_key]);
        }
        coTable[_key] = StartCoroutine(
            DelayActionNext(_delay, _action , () => {
                chine.EndCall();
            } )
        );
        return chine;
    }

    IEnumerator DelayActionNext (float _delay, System.Action _action, System.Action _done )
    {
        yield return new WaitForSeconds(_delay);
        _action.Invoke();
        _done.Invoke();
    }


    protected Chaine AnimateVector3(string _key, Vector3 _from, Vector3 _to, float _duration, AnimationCurve curve, System.Action<Vector3> _callback )
    {
        Chaine chine = new Chaine();
        if(coTable[_key] != null)
        {
            StopCoroutine((Coroutine)coTable[_key]);
        }
        coTable[_key] = StartCoroutine(  
            AniVector3( _from, _to, _duration, curve,
            _callback,
            () => {
                coTable[_key] = null;
                chine.EndCall();
            } ) 
        );
        return chine;
    }

    IEnumerator AniVector3(
        Vector3 _from,
        Vector3 _to,
        float _duration,
        AnimationCurve curve,
        System.Action<Vector3> _frame,
        System.Action _done
    )
    {

        float time = Time.time;
        while (Time.time - time < _duration)
        {
            float value = (Time.time - time) / _duration;
            _frame.Invoke(Vector3.Lerp(_from, _to, (curve == null ? value : curve.Evaluate(value))));
            yield return null;
        }
        _frame.Invoke(_to);
        _done.Invoke();
    }


    protected Chaine AnimateFloat(string _key, float _from, float _to, float _duration, AnimationCurve curve, System.Action<float> _callback )
    {
        Chaine chine = new Chaine();
        curve = (curve == null ? defaultCurve : curve);
        if(coTable[_key] != null)
        {
            StopCoroutine((Coroutine)coTable[_key]);
        }
        coTable[_key] = StartCoroutine(
            AniFloat( _from, _to, _duration, curve,
            _callback,
            () => {
                coTable[_key] = null;
                chine.EndCall();
            } ) 
        );
        return chine;
    }

    IEnumerator AniFloat(
        float _from,
        float _to,
        float _duration,
        AnimationCurve curve,
        System.Action<float> _frame,
        System.Action _done        
    )
    {
        float time = Time.time;
        while (Time.time - time < _duration)
        {
            float value = (Time.time - time) / _duration;
            _frame.Invoke(Mathf.Lerp(_from, _to,  (curve == null ? value : curve.Evaluate(value)) )  );
            yield return null;
        }
        _frame.Invoke(_to);
        _done.Invoke();       
    }

    protected void AnimateCurve(string _key, float _duration, AnimationCurve _curve, System.Action<float> _callback)
    {
        if (coTable[_key] != null)
        {
            StopCoroutine((Coroutine)coTable[_key]);
        }
        coTable[_key] = StartCoroutine(
            AniCurve(_duration, _curve,
            _callback,
            () =>
            {
                coTable[_key] = null;
            })
        );
    }

    IEnumerator AniCurve(
        float _duration,
        AnimationCurve curve,
        System.Action<float> _frame,
        System.Action _done 
    )
    {
        float time = Time.time;
        while (Time.time - time < _duration)
        {
            float value = (Time.time - time) / _duration;
            _frame.Invoke(curve.Evaluate(value));
            yield return null;
        }
        _frame.Invoke(curve.Evaluate(1f));
        _done.Invoke();
    }

    public class Chaine 
    {
        System.Action callback = null;
        public void End(System.Action _end)
        {
            callback = _end;
        }
        public void EndCall()
        {
            if(callback == null)
            {
                return;
            }
            callback.Invoke();
        }
    }

}
