using UnityEngine;
using UnityEngine.UI;

public class Interupt : InteractableObject {

    [SerializeField] private GameObject messageElectricity;

    private const float timeToFade = 5;

    private static float fps = 30;

    private static Text text;

    private static bool isFading = false;

    private static float alpha = 1f;

    public static bool thereIsElectricity = false;   // Mettre à False

    private static bool isOn = false;

    private static Vector3 isOnPos = new Vector3(-130.964f, 45.5173f, -60.36671f);
    private static Vector3 isOnRot = new Vector3(0.6414795f, 179.5865f, -99.2149f);

    private static Vector3 isOffPos = new Vector3(-130.9664f, 45.51999f, -60.36671f);
    private static Vector3 isOffRot = new Vector3(0.1533813f, 0.1533813f, 12.72858f);

    private static Interupt instance = null;

    private static GameObject messageElectricityStatic = null;

    public static bool messageAppeared = false;

    public GameObject ConeLight;

    public static bool Allume = false;

    protected override void Start() {
        base.Start();
        if (messageElectricity != null) {
            messageElectricity.SetActive(false);
            text = messageElectricity.GetComponent<Text>();
        }
        UpdateTransform();
        if (instance != null) {
            Debug.LogError("Error : Only one instance of Interupt must be running at a time !");
            return;
        }
        instance = this;
        messageElectricityStatic = messageElectricity;
    }

    protected override void DoActionDown() {
        CheckElectricity();
        Switch();
        SoundManager.PlaySound("switch");
        if(isOn && Interupt.thereIsElectricity){
            ConeLight.SetActive(true);
            Allume = true;
        }
        else{
            ConeLight.SetActive(false);
            Allume = false;
        }
    }

    public static void CheckElectricity() {
        if (!thereIsElectricity) {
            if (!isFading) {
                messageElectricityStatic.SetActive(true);
                isFading = true;
                messageAppeared = true;
                instance.InvokeRepeating("Fade", 0, 1 / fps);
            }
        }
    }

    void Fade() {
        alpha -= 1 / (fps * timeToFade);
        text.color = new Color(1, 1, 1, alpha);
        if (alpha < 0) {
            isFading = false;
            messageElectricity.SetActive(false);
            alpha = 1;
            text.color = new Color(1, 1, 1, alpha);
            CancelInvoke("Fade");
        }
    }

    void Switch() {
        isOn = !isOn;
        UpdateTransform();
    }

    void UpdateTransform() {
        transform.localPosition = (isOn ? isOnPos : isOffPos);
        transform.localEulerAngles = (isOn ? isOnRot : isOffRot);
    }
}