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

public class UITextInput : MonoBehaviour
{
    public bool Editable => InputField.interactable;
    public TMPro.TMP_Text Label;
    public TMPro.TMP_InputField InputField;
    public InputMode Mode;

    public enum InputMode
    {
        Text,
        FilePicker,
        FolderPicker
    }

    public static UITextInput Create(string name, string defaultText, bool editable, Transform parent, InputMode mode = InputMode.Text)
    {
        var input = Instantiate(SharedResources.Instance.UITextInput, parent);
        input.Init(name, defaultText, editable, mode);
        return input;
    }

    public void Init(string name, string defaultText, bool editable, InputMode mode)
    {
        Mode = mode;
        Label.text = name;
        InputField.text = defaultText;
        InputField.interactable = editable;
        switch (mode)
        {
            case InputMode.FilePicker:
                {
                    InputField.onSelect.AddListener(
                        (text) =>
                        {
                            var result = SFB.StandaloneFileBrowser.OpenFilePanel(name, InputField.text, "", false);
                            if (result.Length == 0) return;
                            InputField.text = result[0];
                        }
                    );
                    break;
                }
            case InputMode.FolderPicker:
                {
                    InputField.onSelect.AddListener(
                        (text) =>
                        {
                            var result = SFB.StandaloneFileBrowser.OpenFolderPanel(name, InputField.text, false);
                            if (result.Length == 0) return;
                            InputField.text = result[0] + "//";
                        }
                    );
                    break;
                }
        }
    }

    public void SetOnTextChanged(UnityAction<string> action)
    {
        InputField.onEndEdit.RemoveAllListeners();
        InputField.onEndEdit.AddListener(action);
    }
}
