using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using static UnityEngine.EventSystems.StandaloneInputModule;
public class UndoRedoJob : MonoBehaviour
{
public TMP_InputField InputText;
public Button BtnUndo;
public Button BtnRedo;
private readonly Stack<string> _editingHistory = new();
private readonly Stack<string> _undoHistory = new();
private bool IsFirst = false;
private void OnEnable()
{
_editingHistory.Clear();
_editingHistory.Push(InputText.text);
BtnUndo.interactable = false;
BtnRedo.interactable = false;
InputText.onValueChanged.AddListener(History);
BtnUndo.onClick.AddListener(Undo);
BtnRedo.onClick.AddListener(Redo);
}
private void History(string inputCode)
{
if (_editingHistory.TryPeek(out string s))
{
if (s is null or "")
{
_editingHistory.Pop();
}
}
if (inputCode != s)
{
_editingHistory.Push(inputCode);
BtnUndo.interactable = IsFirst;
_undoHistory.Clear();
BtnRedo.interactable = false;
}
IsFirst = true;
}
private void Undo()
{
if (_editingHistory.Count > 1)
{
_undoHistory.Push(_editingHistory.Pop());
if (_editingHistory.TryPeek(out string s))
{
BtnUndo.interactable = true;
InputText.text = s;
BtnRedo.interactable = _editingHistory.Count > 0;
}
}
else
{
BtnUndo.interactable = false;
}
}
private void Redo()
{
if (_undoHistory.Count > 1)
{
_editingHistory.Push(_undoHistory.Pop());
//BtnRedo.interactable = _undoHistory.Count > 0;
InputText.text = _editingHistory.Peek();
BtnUndo.interactable = true;
}
else
{
BtnRedo.interactable = false;
}
}
}