using UnityEngine;

public class ButtonGrotte : Button 
{
    private Renderer myRenderer = null;
    public GameObject affichageChiffres;
    private const string combinaison = "151";
    private static Material[] chiffresSprite = null;
    private int myNumber = 0;
    private int myIndex = -1;
    private static int nbToWin = 0;
    private static int nbWon = 0;
    private bool isValid = false;
    public static bool porteOuverte = false;
   
    protected override void Start()
    {
        base.Start();
        myIndex = gameObject.name[gameObject.name.Length - 1] - '0' - 1;
        chiffresSprite = Resources.LoadAll<Material>("Chiffres/Materials");
        do {
            myNumber = Random.Range(0, chiffresSprite.Length);
        } while (myNumber == combinaison[myIndex] - '0');
        myRenderer = affichageChiffres.GetComponent<Renderer>();
        nbToWin++;
        ApplyNumber();
    }

    protected override void DoActionUp()
    {
        base.DoActionUp();
        if (!porteOuverte)
        {
            myNumber = (myNumber + 1) % chiffresSprite.Length;
            ApplyNumber();
            CheckIfValid();
        }
    }

    void ApplyNumber()
    {
        myRenderer.material = chiffresSprite[myNumber];
    }

    void CheckIfValid()
    { 
        if(myNumber == combinaison[myIndex]-'0')
        {
            nbWon++;
            isValid = true;
        }
        else if (isValid && myNumber != combinaison[myIndex]-'0')
        {
            nbWon--;
            isValid = false;
        }
        if (nbToWin == nbWon)
        {
            porteOuverte = true;
            SoundManager.PlaySound("porteGrotte");
        }
    }
}