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

public class GFStates
{
    public float time = 0;
    public float duration = -1;
    public string state = "";

    private MonoBehaviour m_script;
    private MethodInfo m_miUpdate;

    public GFStates(MonoBehaviour script)
    {
        m_script = script;
    }

    public void Reset()
    {
        Change("");
    }

    public void Change(string _state, float _duration = -1)
    {
        string nextState = _state;
        float nextDuration = _duration;

        if (state != "")
        {
            string old = state;
            state = "";
            OnStop(old);

            if (state != "")
                return;
        }

        state = nextState;
        duration = nextDuration;

        nextState = "";
        nextDuration = -1;

        if (state != "")
            OnStart();
    }

    private void OnStart()
    {
        time = 0;

        m_miUpdate = m_script.GetType().GetMethod("OnUpdate" + state);

        MethodInfo m = m_script.GetType().GetMethod("OnStart" + state);
        if(m != null)
            m.Invoke(m_script, null);
    }

    private void OnStop(string _state)
    {
        m_miUpdate = null;

        MethodInfo m = m_script.GetType().GetMethod("OnStop" + _state);
        if (m != null)
            m.Invoke(m_script, null);
    }

    public void OnUpdate()
    {
        time += Time.deltaTime;

        if (m_miUpdate != null)
            m_miUpdate.Invoke(m_script, null);

        // this allows users to change their state on the OnStop callback
        if (duration != -1 && time > duration)
            Reset();
    }

}