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

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

    [Header("Settings")]
    [SerializeField] private float _angleToRotate = 0;
    [SerializeField] private bool _isFirstStart = true;
    [SerializeField] private bool _isMainPowerSwitch = false;

    [Header("Assets")]
    [SerializeField] private BoolVariable _switchOn = default;
    [SerializeField] private GameEvent _switchStateChangeEvent = default;

    [Header("Refs")]
    [SerializeField] private GameObject _switchArt = default;
    [SerializeField] private Selectable _selectable = default;
    [SerializeField] private AudioSource _playOnSelect = default;
    [SerializeField] private AudioSource _playOnPowerUp = default;
    [SerializeField] private AudioSource _playOnPowerDown = default;
    [SerializeField] private AudioSource _playOnIdle = default;

    private void Start()
    {
        SetRotation();
        _isFirstStart = false;
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        if (!_selectable.Locked)
        {
            if (_selectable.Selected)
            {
                ChangeSwitchState();
            }
            else
            {
                _selectable.Select();
                ChangeSwitchState();
            }
        }
    }

    private void ChangeSwitchState()
    {
        SwitchOn = !SwitchOn;
        _switchOn.Value = SwitchOn;
        _switchStateChangeEvent.Raise();
        SetRotation();
    }

    private void SetRotation()
    {
        var angleMod = SwitchOn ? 1 : -1;

        var currentAngles = _switchArt.transform.localEulerAngles;
        var newAngle = new Vector3(currentAngles.x, currentAngles.y, _angleToRotate * angleMod);
        _switchArt.transform.localEulerAngles = newAngle;
        // PLAY A SOUND
        if (!_isFirstStart)
        {
            if (_isMainPowerSwitch)
            {
                if (!SwitchOn)
                {
                    _playOnSelect.Play();
                    _playOnIdle.Stop();
                    _playOnPowerDown.Play();
                }
                else
                {
                    _playOnSelect.Play();
                    _playOnPowerUp.Play();
                    _playOnIdle.PlayDelayed(7);
                }
            }
            else
            {
                _playOnSelect.Play();
            }
        }
    }
}
