using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class StackNode : MonoBehaviour
{
    [SerializeField] private float rotationSpeed = 10f;
    [SerializeField] private float descendTime = 0.2f;
    [SerializeField] private float nodeHeight = 1f;
    public int score = 100;

    private Movable movable;
    private float nodeHeightDistance = 0.1f;

    private void Awake()
    {
        movable = gameObject.GetComponent<Movable>();
    }

    void Start()
    {
        GameEvents.instance.onHitEvent += Descend;
        GameEvents.instance.onGameLostEvent += FreezeYPosition;
        GameEvents.instance.onGameRestartEvent += UnfreezeYPosition;
    }

    void FixedUpdate()
    {
        transform.localEulerAngles += new Vector3(0f, rotationSpeed * Time.fixedDeltaTime, 0f);
    }

    private void OnDestroy()
    {
        GameEvents.instance.onHitEvent -= Descend;
        GameEvents.instance.onGameLostEvent -= FreezeYPosition;
        GameEvents.instance.onGameRestartEvent -= UnfreezeYPosition;
    }

    public float GetNodeHeight()
    {
        return nodeHeight;
    }

    public float GetNodeHeightDifference()
    {
        return nodeHeightDistance;
    }

    private void Descend()
    {
        movable.SetDestination(new Vector3(transform.position.x, movable.targetPosition.y - (nodeHeight + nodeHeightDistance), transform.position.z), descendTime);
    }

    private void FreezeYPosition()
    {
        GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePosition | RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ;
    }

    private void UnfreezeYPosition()
    {
        GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ;
    }
}
