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

public class Obstacle : MonoBehaviour
{
    private Vector3 initialBlockPosition;
    private bool freezePosition = true;

    private void Start()
    {
        GameEvents.instance.onGameLostEvent += TurnOnGravity;
        GameEvents.instance.onGameLostEvent += stopPositionFreeze;
        if (transform.childCount == 1) {
            initialBlockPosition = transform.GetChild(0).localPosition;
        }
    }

    private void Update()
    {
        // keep localPosition freezed
        if (transform.childCount == 1 && freezePosition)
        {
            transform.GetChild(0).localPosition = initialBlockPosition;
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag.Equals("Cannonball"))
        {
            if (other.gameObject.GetComponent<Cannonball>().hasHitObstacle == false)
                other.gameObject.GetComponent<Movable>().UnoReverseCard();
            other.gameObject.GetComponent<Cannonball>().HitObstacle();
        }
    }

    private void TurnOnGravity()
    {
        GetComponentInChildren<Collider>().isTrigger = false;
    }

    private void stopPositionFreeze()
    {
        freezePosition = false;
    }

    private void OnDestroy()
    {
        GameEvents.instance.onGameLostEvent -= TurnOnGravity;
        GameEvents.instance.onGameLostEvent -= stopPositionFreeze;
    }
}
