namespace InABox.Avalonia.Router;

public class Router<TViewModelBase> where TViewModelBase:class
{

    private TViewModelBase _currentViewModel = default!;
    protected readonly Func<Type, TViewModelBase> CreateViewModel;
    
    
    public event Action<TViewModelBase>? CurrentViewModelChanged;

    public Router(Func<Type, TViewModelBase> createViewModel)
    {
        CreateViewModel = createViewModel;
    }

    protected TViewModelBase CurrentViewModel
    {
        set
        {
            if (value == _currentViewModel) return;
            _currentViewModel = value;
            OnCurrentViewModelChanged(value);
        }
    }

    private void OnCurrentViewModelChanged(TViewModelBase viewModel)
    {
        CurrentViewModelChanged?.Invoke(viewModel);
    }

    public virtual T GoTo<T>(Action<T>? configure) where T : TViewModelBase
    {
        var viewModel = InstantiateViewModel<T>(configure);
        CurrentViewModel = viewModel;
        return viewModel;
    }

    public T InstantiateViewModel<T>(Action<T>? configure) where T : TViewModelBase
    {
        var result = (T)Convert.ChangeType(CreateViewModel(typeof(T)), typeof(T));
        configure?.Invoke(result);
        return result;
    }

}