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

public class Stack : MonoBehaviour
{
    [SerializeField] private int numberOfNodes;
    [SerializeField] private float nodeMultiplyer = 1.2f;
    [HideInInspector] public int nodesLeft;

    private int initialNodeCount;
    
    private NodeHolder nodeHolder = null;

    void Awake()
    {
        initialNodeCount = numberOfNodes;
        nodeHolder = gameObject.transform.GetChild(0).GetComponent<NodeHolder>();
        refreshStack(numberOfNodes);
    }

    private void Start()
    {
        GameEvents.instance.onGameRestartEvent += RestartStack;
    }

    private void refreshStack(int nodeCount)
    {
        numberOfNodes = nodesLeft = nodeCount;
        nodeHolder.MakeNodes(numberOfNodes);
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Cannonball")
        {
            GameEvents.instance.TriggerOnHitEvent();
            // Destroy the last stack node
            collision.gameObject.GetComponent<Cannonball>().HitNode();
            Destroy(collision.gameObject);
            ScoreKeeper.instance.IncrementScore(nodeHolder.GetBottomNode().gameObject.GetComponent<StackNode>().score);
            nodeHolder.RemoveBottomNode();
            nodesLeft--;

            if(nodesLeft == 0)
            {
                GameEvents.instance.TriggerOnNextLevelEvent();
                refreshStack((int)(numberOfNodes * nodeMultiplyer));
            }
        }
    }

    private void RestartStack()
    {
        numberOfNodes = initialNodeCount;
        nodeHolder = gameObject.transform.GetChild(0).GetComponent<NodeHolder>();
        refreshStack(numberOfNodes);
    }
}
