using UnityEngine;
using System.Collections;
using UnityEditor;

[AddComponentMenu("MGUB Event Editor/Random Event")]
public class RandomEvent : SceneEvent {
    public bool doNotStartWhenCanInteract = true;
    public float averageTime = 30.0f;
    public float fluctuation = 0.8f;
    private float currentTime = -1.0f;
    private float time = 0.0f;

    // Update is called once per frame
    void Update() {
        if (!running && !completed) {
            if (currentTime < 0.0f) {
                SetCurrentTime();
            }
            bool canStart = scriptRunning == null;
            if (doNotStartWhenCanInteract) {
                canStart = canStart && !(InteractiveTrigger.lastFacingInteractor != null && InteractiveTrigger.lastFacingInteractor.interactable);
            }
            if (canStart) {
                time += Time.deltaTime;
            }
            else {
                if (time > 0.0f) {
                    time = 0.0f;
                }
            }
            if (time >= currentTime) {
                time = 0.0f;
                SetCurrentTime();
                Run();
            }
        }
        else {
            Run();
        }
	}

    private void SetCurrentTime() {
        if (averageTime < 0.0f) {
            currentTime = 9999.0f;
        }
        else {
            currentTime = Random.Range(averageTime * (1.0f - fluctuation), averageTime * (1.0f + fluctuation));
        }
    }

    public void Reset() {
        this.canBeInterrupted = true;
        this.looping = true;
    }

}
