using System;
using System.Reflection;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using CommunityToolkit.Mvvm.DependencyInjection;
using PSCHelpdesk.Services;
using PSCHelpdesk.Shared.ViewModels;

namespace PSCHelpdesk;

public class ViewLocator : IDataTemplate
{
    private PluginService _pluginService;

    
    public Control? Build(object? data)
    {
        if (_pluginService == null)
        {
            _pluginService = Ioc.Default.GetService<PluginService>();
        }
        if (data is null)
            return null;

        var name = data.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
        var type = Type.GetType(name);

        if (_pluginService.ViewExists(name))
        {
            var v = _pluginService.GetView(name);
            return v;
        }
        
        if (type != null)
        {
            return (Control)Activator.CreateInstance(type)!;
        }

        return new TextBlock { Text = "Not Found: " + name };
    }

    public bool Match(object data)
    {
        var l = data is IViewModelBase;
        return l;
    }
}