using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using VRTK;

public class Grimoire : MonoBehaviour {
  //if Grimoire is in hand
  public bool Holding = false;

  //UI handler
  public GameObject UIhandler;
  private UIHandlerScript UIS;

  //VR Controllers
  public GameObject RightController;
  private VRTK_ControllerEvents RCE;
  private VRTK_InteractGrab RCG;
  public GameObject LeftController;
  private VRTK_ControllerEvents LCE;
  private VRTK_InteractGrab LCG;

  //Items in hand
  public GameObject GrabLeft;
  public GameObject GrabRight;

  //Button Settings
  private bool MayButton = true;
  public float waitbuttonTime = 1f;

  //When this object spawns
  void Awake () {
   UIS = UIhandler.GetComponent ();
   RCE = RightController.GetComponent ();
   LCE = LeftController.GetComponent ();
   RCG = RightController.GetComponent();
   LCG = LeftController.GetComponent();
  }

  // Update is called once per frame
  void Update () {
   CheckHolding();
   CheckGrimoireSee ();
  }

  //Check if holding grimoire
  void CheckHolding()
  {
   GrabRight = RCG.GetGrabbedObject();
   GrabLeft = LCG.GetGrabbedObject();
  
   if(GrabRight == gameObject || GrabLeft == gameObject)
   {
    Holding = true;
   }
   else
   {
    Holding = false;
   }
  }

  //Check which page to view
  void CheckGrimoireSee(){
   if (Holding) {
    if (RCE.triggerPressed || LCE.triggerPressed) {
     UIS.GrimoireUp = true;
     if ((RCE.buttonOnePressed || LCE.buttonOnePressed) && MayButton) {
      if (UIS.AtPage == 1) {
       UIS.AtPage = 2;
       StartCoroutine(WaitButton());
      }
      else if (UIS.AtPage == 2) {
       UIS.AtPage = 3;
       StartCoroutine(WaitButton());
      }
      else if (UIS.AtPage == 3) {
       UIS.AtPage = 4;
       StartCoroutine(WaitButton());
      }
      else if (UIS.AtPage == 4) {
       UIS.AtPage = 1;
       StartCoroutine(WaitButton());
      }
      print("Pressed A");
     }
     if ((RCE.buttonTwoPressed || LCE.buttonTwoPressed) && MayButton) {
      if (UIS.AtPage == 1) {
       UIS.AtPage = 4;
       StartCoroutine(WaitButton());
      }
      else if (UIS.AtPage == 2) {
       UIS.AtPage = 3;
       StartCoroutine(WaitButton());
      }
      else if (UIS.AtPage == 3) {
       UIS.AtPage = 4;
       StartCoroutine(WaitButton());
      }
      else if (UIS.AtPage == 4) {
       UIS.AtPage = 1;
       StartCoroutine(WaitButton());
      }
      print("Pressed B");
     }
    }
    if (!RCE.triggerPressed && !LCE.triggerPressed) {
     UIS.GrimoireUp = false;
    }
   
   }
   if (!Holding) {
    UIS.GrimoireUp = false;
   }
  }

  //Button spam protection
  IEnumerator WaitButton()
  {
   print("Waiting");
   MayButton = false;
   yield return new WaitForSeconds(waitbuttonTime);
   MayButton = true;
  }

}//CLASS