using UnityEngine;

public class RotateMoulin : MonoBehaviour {

    enum SonMoulin {ACCELERATING, DECELERATING, MARCHING };

    private float speedMoulin = 0;

    private static float maxSpeedMoulin = 100f;

    private const float fps = 30f;

    private static float accelerationCoeff = 0.7f;

    private static RotateMoulin instance = null;

    private static AudioSource sonMoulin = null;

    private static AudioClip[] sonsMoulin = null;

    void Start() {
        if (instance != null) {
            Debug.LogError("Error : there must only be one instance of RotateMoulin running at a time !");
            return;
        }
        instance = this;
        sonMoulin = GameObject.Find("SonMoulin").GetComponent<AudioSource>();
        sonsMoulin = Resources.LoadAll<AudioClip>("Sounds/Moulin");
    }

    void Update() {
        transform.Rotate(Vector3.up * speedMoulin * Time.deltaTime);
    }

    public static void RotateOn() {
        instance.CancelInvoke("Decelerate");
        UpdateSonMoulin(SonMoulin.ACCELERATING);
        instance.InvokeRepeating("Accelerate", 0, 1 / fps);
    }

    public static void RotateOff() {
        instance.CancelInvoke("Accelerate");
        UpdateSonMoulin(SonMoulin.DECELERATING);
        instance.InvokeRepeating("Decelerate", 0, 1 / fps);
    }

    void Accelerate() {
        speedMoulin += accelerationCoeff;
        if (speedMoulin >= maxSpeedMoulin) {
            CancelInvoke("Accelerate");
            speedMoulin = maxSpeedMoulin;
            UpdateSonMoulin(SonMoulin.MARCHING, true);
        }
    }

    void Decelerate() {
        speedMoulin -= accelerationCoeff;
        if (speedMoulin <= 0) {
            CancelInvoke("Decelerate");
            speedMoulin = 0;
        }
    }

    static void UpdateSonMoulin(SonMoulin s, bool looping = false) {
        sonMoulin.Stop();
        sonMoulin.clip = sonsMoulin[(int)s];
        sonMoulin.Play();
        sonMoulin.loop = looping;
    }
}