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

public class UpgradeScreenGodHand : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    static int[] Costs = { 3, 3, 4, 4 };
    // Update is called once per frame
    void Update()
    {

        RaycastHit cardHit;
        Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out cardHit);
        if (cardHit.collider != null)
        {
            GameObject logicalObject = cardHit.collider.gameObject;
            while (logicalObject.GetComponent<CardInstance>() == null && logicalObject.transform.parent != null)
                logicalObject = logicalObject.transform.parent.gameObject;

            CardInstance ci = logicalObject.GetComponent<CardInstance>();

            SetHoveredCard(ci);
        }
        else
        {
            SetHoveredCard(null);
        }

        if (Input.GetMouseButtonDown(0))
        {
            if (hoveredCard != null)
            {
                CardInstance cardToBuy = hoveredCard;
                SetHoveredCard(null);

                // Buy the hovered card
                int index = cardToBuy.GetBlackboardInt("Index");
                int cost = Costs[index];

                PlayerStats.MaxHealth -= cost;
                PlayerStats.Deck.Add(cardToBuy.CardTemplate.CardName);

                cardToBuy.gameObject.FloatText("Added to Deck");

                Object.Destroy(cardToBuy.gameObject);
            }
        }

    }

    CardInstance hoveredCard = null;

    private void SetHoveredCard(CardInstance target)
    {
        if (hoveredCard == target)
            return;

        if (hoveredCard != null)
        {
            GetComponent<UpgradeScreen>().UnhoverCard(hoveredCard);
        }

        if (target != null)
        {
            GetComponent<UpgradeScreen>().HoverCard(target);
        }

        hoveredCard = target;
    }
}
