using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

public class PopupController : MonoBehaviour
{
    public Transform PopupPanel;
    public float offset;
    public int side;
    public UIHandle Owner;
    GameObject ButtonPrefab;
    public Dictionary<GameObject, System.Func<bool>> ConditionalButtons = new Dictionary<GameObject, System.Func<bool>>();

    public void AddButton(string name, System.Action callback)
    {
        Button b = Instantiate(ButtonPrefab, PopupPanel).GetComponent<Button>();
        b.onClick.AddListener(()=>callback.Invoke());
        b.GetComponentInChildren<Text>().text = name;
    }

    public void AddConditionalButton(string name, System.Func<bool> condition, System.Action callback)
    {
        Button b = Instantiate(ButtonPrefab, PopupPanel).GetComponent<Button>();
        b.onClick.AddListener(() => callback.Invoke());
        b.GetComponentInChildren<Text>().text = name;
        ConditionalButtons.Add(b.gameObject, condition);
    }

    private void Update()
    {
        float pos;
        if(Camera.main.WorldToScreenPoint(Owner.transform.position).x < Camera.main.pixelWidth / 2 - side)
        {
            side = -1;
        }
        else
        {
            side = 1;
        }
        pos = side * Camera.main.pixelWidth / 20 + offset;
        transform.position = Camera.main.WorldToScreenPoint(Owner.transform.position) + pos * Vector3.right;

        foreach(var kv in ConditionalButtons)
        {
            kv.Key.gameObject.SetActive(kv.Value.Invoke());
        }
    }

    public PopupController Init(UIHandle owner)
    {
        Owner = owner;
        transform.SetAsFirstSibling();
        GetComponentInChildren<Text>().text = owner.name;
        PopupPanel = transform.Find("PopupPanel");
        ButtonPrefab = Resources.Load(Strings.PopupButtonPrefab) as GameObject;
        return this;
    }
}
