using UnityEngine;
using UnityEngine.Experimental.Rendering.LWRP;
using CorgiLabs.Utility;

public class LightBulb : GhostEventSource, ITriggerable, IInteractable
{
    [Range(0, 1)]
    [SerializeField] private float m_BreakChance;

    [SerializeField] private SoundEffect m_ScrewSound;

    [SerializeField] private Sprite m_NormalSprite;
    [SerializeField] private Sprite m_BrokenSprite;

    private Light2D m_Light;

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

    private SpriteRenderer m_SpriteRenderer;

    private void Awake()
    {
        m_Light = GetComponentInChildren<Light2D>();
        m_SpriteRenderer = GetComponentInChildren<SpriteRenderer>();
    }

    public void Trigger(byte triggerId)
    {
        if (!m_IsBroken)
        {
            if (Random.Range(0.0f,1.0f) <= m_BreakChance)
            {
                EventManager.TriggerEvent(EventID.GhostEventStart, this);

                if (m_IsBroken)
                    return;
            }

            m_Light.enabled = !m_Light.enabled;
        }
    }

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

            actor.Sleep();

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


            actor.StickRotationSprite.SetActive(true);
            ServiceLocator.Get<InputHandler>().RequireStickRotation(actor.Index, completionHandler);
        }
    }

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

        m_IsBroken = true;
        m_Light.enabled = false;

        m_SpriteRenderer.sprite = m_BrokenSprite;

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

    private void Repair()
    {
        m_IsBroken = false;
        m_IsRepairing = false;
        m_Light.enabled = true;

        m_ScrewSound?.Play(transform.position);

        m_SpriteRenderer.sprite = m_NormalSprite;

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