using UnityEngine;
using UnityEngine.UI;

public class Page : InteractableObject {

    private static Material[] pagesMat = null;

    private static int idxFound;

    private static Text nbPages = null;

    private int myIdx = -1;

    protected override void Start() {
        idxFound = -1;
        base.Start();
        pagesMat = Resources.LoadAll<Material>("Sprites/Pages");
        nbPages = GameObject.Find("NbPages").GetComponent<Text>();
        nbPages.enabled = false;
    }

    protected override void DoActionDown() {
        if (!PlayerBehaviour.isLookingItem) {
            if (idxFound == -1) {
                nbPages.enabled = true;
            }
            idxFound++;
            nbPages.text = "Pages : " + (idxFound + 1) + " / 3";
            myIdx = idxFound;
            if (idxFound == pagesMat.Length-1) {
                transform.localScale = new Vector3(transform.localScale.x * 2, transform.localScale.y, transform.localScale.z);
            }
            GetComponent<Renderer>().material = pagesMat[idxFound];
            GetComponent<Renderer>().material.shader = highlightShader;
            transform.LookAt(Camera.main.transform);
            transform.Rotate(Vector3.right * 75);
            transform.position = Camera.main.transform.position + Camera.main.transform.forward;
            Invoke("SetLookingItem", 0.05f);
            SoundManager.PlaySound("take_page");
        }
    }

    protected override void Update() {
        base.Update();
        if (myIdx == idxFound && PlayerBehaviour.isLookingItem && (Input.GetMouseButtonDown(0) || Input.GetButtonDown("Action"))) {
            PlayerBehaviour.isLookingItem = false;
            if (idxFound == pagesMat.Length-1) {
                // On a fini de lire la dernière page, on met la nuit
                Sun.FadeToNight();
            }
            Destroy(gameObject);
        }
    }

    void SetLookingItem() {
        PlayerBehaviour.isLookingItem = true;
    }
}