using System.Collections;
using System.Collections.Generic;
using System.Linq; 
using UnityEngine;

public class PressurePlate : InteractableObject
{
    private bool pressed = false;
    private int itemId = 0;
    private Vector3 initialScale;
    private GameObject preview;

    public delegate void PressurePlatePressed(bool val); 
    public event PressurePlatePressed OnPressedChanged;

    public bool Pressed 
    {
        get
        {
            return pressed; 
        }
    }

    public void SetItem(int itemId)
    {
        if (preview != null)
        {
            Destroy(preview);
        }

        if (itemId != 0)
        {
            press(true, Player.Instance); 
            this.itemId = itemId; 
            Item i = ItemManager.Instance.SpawnWeapon(itemId);
            preview = i.gameObject;
            preview.transform.position = this.transform.position; 
            initialScale = preview.transform.localScale;
            Destroy(i); // Destroys the Item Script, not the preview GameObject instance 
        }
    }

    private void press(bool value, Entity e)
    {
        Debug.Log("Press " + value); 
        pressed = value;
        if(OnPressedChanged != null)
        {
            OnPressedChanged(value); 
        }
    }

    public void FixedUpdate()
    {
        if (Player.Instance != null)
        {
            if ((Player.Instance.transform.position - this.transform.position).magnitude < 1.0f)
            {
                if (!pressed && itemId == 0)
                {
                    press(true, Player.Instance);
                }
            }
            else 
            {
                if(pressed && itemId == 0)
                {
                    press(false, Player.Instance);
                }
            }
        }
    }

    public override void OnInteract(Entity caller)
    {
        if(itemId != 0)
        {
            UserInterface.Instance.DisplayMessage("PRESSURE PLATE IS ALREADY OCCUPIED.", 909.0f, 3.0f);
        }
        
        if (itemId == 0) 
        {
            if(Player.Instance.Inventory.GetItems().Where(x => x != 0).Count() == 0)
            {
                UserInterface.Instance.DisplayMessage("YOU'VE GOT NOTHING TO SACRIFICE.", 750.0f, 3.0f);
            }
            else
            {
                UserInterface.Instance.SetShowSacrificeMenu(pressed ? this : null);
            }
        }
    }

}
