using System;
using Darkmatter.Core.Contracts.Features.History;
using VContainer.Unity;

namespace Darkmatter.Features.History
{
    public class HistoryButtonsPresenter : IStartable, IDisposable
    {
        private readonly HistoryButtonsView _view;
        private readonly IUndoStack _undoStack;

        public HistoryButtonsPresenter(IUndoStack undoStack, HistoryButtonsView view)
        {
            _undoStack = undoStack;
            _view = view;
        }

        public void Start()
        {
            _view.OnUndoClicked += HandleUndoClicked;
            _view.OnRedoClicked += HandleRedoClicked;
            _view.OnClearClicked += HandleClearClicked;
            UpdateButtonUI();
            _undoStack.OnStackChanged += UpdateButtonUI;
        }

        private void HandleClearClicked()
        {
            _undoStack.Clear();
        }

        private void HandleRedoClicked()
        {
            _undoStack.Redo();
        }

        private void HandleUndoClicked()
        {
            _undoStack.Undo();
        }

        private void UpdateButtonUI()
        {
            _view.SetUndoInteractable(_undoStack.CanUndo);
            _view.SetRedoInteractable(_undoStack.CanRedo);
            _view.SetClearInteractable(_undoStack.CanUndo || _undoStack.CanRedo);
        }

        public void Dispose()
        {
            _view.OnUndoClicked -= HandleUndoClicked;
            _view.OnRedoClicked -= HandleRedoClicked;
            _view.OnClearClicked -= HandleClearClicked;
            _undoStack.OnStackChanged -= UpdateButtonUI;
        }
    }
}