using UnityEngine;

public class Repair : MonoBehaviour
{
    public enum Fixes : ushort
    {
        NONE,
        METAL_PIPE,
        CAN,
        PIZZA_BOX
    }

    public Fixes SelectFix = Fixes.NONE;
    [SerializeField] private ObjectHighlighter objectHighlighter;
    [SerializeField] private GameObject fixPiece;
    [SerializeField] private GameObject particleEffect;
    [SerializeField] private GameObject disableOptionalItem;
    public AudioSource repairSound;
    private Player m_player;
    private BlackBoard m_blackboard;
    private bool m_playerWithinFixDist = false;
    
    // Start is called before the first frame update
    void Start()
    {
        m_player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>();
        m_blackboard = (BlackBoard)FindObjectOfType(typeof(BlackBoard));
    }

    // Update is called once per frame
    void Update()
    {
        ushort fixItemId = (ushort) SelectFix;

        if (m_player.CurrentItem == fixItemId)
        {
            objectHighlighter.enabled = true;

            if (Input.GetKeyDown(KeyCode.E) && m_playerWithinFixDist)
            {
                m_player.CurrentItem = 0;
                objectHighlighter.Reset();
                objectHighlighter.enabled = false;
                m_player.Animator.SetTrigger(AnimationHash.Fix);     
                fixPiece.SetActive(true);
                Instantiate(particleEffect, transform.position, Quaternion.identity);
                ParticleSystem[] particles = particleEffect.GetComponentsInChildren<ParticleSystem>();
                repairSound.Play();
                foreach (var particle in particles)
                {
                    particle.Play();
                }

                if (disableOptionalItem)
                {
                    disableOptionalItem.SetActive(false);
                }

                if (m_blackboard)
                {
                    m_blackboard.FixItems();
                }
            }
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            m_playerWithinFixDist = true;
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            m_playerWithinFixDist = false;
        }
    }
}