using System;
using System.Collections;
using System.Collections.Generic;
using ScriptableObjectArchitecture;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.XR;

public class Button : MonoBehaviour, IPointerClickHandler
{
    [field: SerializeField] public bool Depressed { get; private set; } = false;

    [Header("Settings")]
    [SerializeField] private float _resetDelay = 0;
    [SerializeField] private float _depressDistance = 0;

    [Header("Assets")]
    [SerializeField] private GameEvent _buttonPushEvent = default;

    [Header("Refs")]
    [SerializeField] private Selectable _selectable = default;
    [SerializeField] private GameObject _buttonTop = default;
    [SerializeField] private AudioSource _playOnPress = default;

    private float depressCount = 0;
    private Vector3 startingPosition = default;

    private void Start()
    {
        startingPosition = _buttonTop.transform.localPosition;
    }

    private void Update()
    {
        if (Depressed)
        {
            depressCount -= Time.deltaTime;
            if (depressCount < 0)
            {
                RestoreButton();
                Depressed = false;
            }
        }
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        if (_selectable.Selected && !Depressed)
        {
            ChangeButtonState();
        }
        else if (!Depressed)
        {
            _selectable.Select();
            ChangeButtonState();
        }
    }

    private void ChangeButtonState()
    {
        Depressed = true;
        _buttonPushEvent?.Raise();
        PressButton();
        // SwitchOn = !SwitchOn;
        // _switchOn.SetValue(SwitchOn);
        // SetRotation();
    }

    private void PressButton()
    {
        depressCount = _resetDelay;
        var buttonPosition = _buttonTop.transform.localPosition;
        _buttonTop.transform.localPosition = new Vector3(buttonPosition.x, buttonPosition.y - _depressDistance, buttonPosition.z);
        _playOnPress.Play();
    }

    private void RestoreButton()
    {
        _buttonTop.transform.localPosition = startingPosition;
    }
}
