using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using TMPro;
using UnityEngine;

public class MonolithInterfaceBehavior : MonoBehaviour
{

    public GameObject Level;
    public GameObject UpgradeLevelText;
    public AudioSource AudioBuyNewLand;
    public AudioSource AudioFail;
    public AudioSource AudioUpgrade;

    [HideInInspector]
    public bool IsActive;
    [HideInInspector]
    public GameObject LastMonolith;

    void Start()
    {
        
    }


    void Update()
    {
        GetComponent<CanvasGroup>().alpha = (IsActive ? 1f : 0f);
        if (LastMonolith != null)
        {
            var lastMonolithBehavior = LastMonolith.GetComponent<MonolithBehavior>();
            var level = Level.GetComponent<Level>();
            
            var promptUpgrade = transform.Find("Prompt Upgrade Monolith");
            var upgradeLevel = level.Matrix.Get(Global.PositionToIndex(LastMonolith.transform.position).Identifier).Upgrade;
            var upgradeCost = Global.GetUpgradeCost(upgradeLevel);
            promptUpgrade.transform.Find("Text Upgrade Monolith").GetComponent<TextMeshProUGUI>().text = (upgradeCost < 0f ? "~" : upgradeCost.ToString(CultureInfo.InvariantCulture));
            promptUpgrade.GetComponent<CanvasGroup>().alpha = (upgradeCost < 0f ? 0.2f : 1f);

            UpgradeLevelText.GetComponent<TextMeshProUGUI>().text = upgradeLevel.ToString(CultureInfo.InvariantCulture);

            var promptBuyNewLand = transform.Find("Prompt Buy New Land");
            promptBuyNewLand.transform.Find("Text Buy New Land").GetComponent<TextMeshProUGUI>().text = level.BuyNewLandCost.ToString(CultureInfo.InvariantCulture);
            promptBuyNewLand.GetComponent<CanvasGroup>().alpha = (lastMonolithBehavior.NewLandBought ? 0.2f : 1f);
        }
    }

    public void Show(GameObject monolith)
    {
        if (!IsActive)
        {
            IsActive = true;
            LastMonolith = monolith;
        }
    }

    public void Hide()
    {
        if (IsActive)
        {
            IsActive = false;
        }
    }

    public void PressQ()
    {
        if (!IsActive || LastMonolith == null)
            return;
        var success = Level.GetComponent<Level>().TryUpgradeTile(Global.PositionToIndex(LastMonolith.transform.position));
        if (success)
            AudioUpgrade.Play();
        else
            AudioFail.Play();
        Hide();
    }

    public void PressE()
    {
        if (!IsActive || LastMonolith == null || LastMonolith.GetComponent<MonolithBehavior>().NewLandBought)
            return;
        var success = Level.GetComponent<Level>().TryBuyNewTile();
        if (success)
        {
            AudioBuyNewLand.Play();
            LastMonolith.GetComponent<MonolithBehavior>().NewLandBought = true;
        }
        else
            AudioFail.Play();
        Hide();
    }

}
