using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using CorgiLabs.Utility;

public class Toilet : GhostEventSource, IInteractable
{
    [SerializeField] private int m_RequiredButtonHits;
    [SerializeField] private float m_ButtonHitDepleteDelay;

    [SerializeField] private GameObject m_OpenSprite;
    [SerializeField] private GameObject m_ClosedSprite;

    private AudioSource m_AudioSource;

    private bool m_IsBroken = false;
    private bool m_IsRepairing = false;

    protected virtual void Awake()
    {
        m_AudioSource = GetComponentInChildren<AudioSource>();
    }

    public void Interact(PlayerController actor)
    {
        if (m_IsBroken && !m_IsRepairing)
        {
            m_IsRepairing = true;

            actor.Sleep();

            Callback completionHandler = Repair;
            completionHandler += actor.WakeUp;

            actor.ButtonMashSprite.SetActive(true);
            m_AudioSource?.Play();
            ServiceLocator.Get<InputHandler>().RequireButtonMash(actor.Index, m_RequiredButtonHits, m_ButtonHitDepleteDelay, completionHandler);
        }
    }

    public override void StartEvent()
    {
        base.StartEvent();


        m_OpenSprite.SetActive(false);
        m_ClosedSprite.SetActive(true);

        m_IsBroken = true;
        ServiceLocator.Get<GhostSpawner>().SpawnAt(transform.position);
    }

    protected virtual void Repair()
    {
        m_IsBroken = false;
        m_IsRepairing = false;

        m_OpenSprite.SetActive(true);
        m_ClosedSprite.SetActive(false);

        m_AudioSource?.Stop();
        EventManager.TriggerEvent<GhostEventSource>(EventID.GhostEventSuccess, this);
    }
}
