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 PluginManager _pluginService;

    
    public Control? Build(object? data)
    {
        if (data is null)
            return null;
        
        var originalName = data.GetType().FullName;
        
        if (_pluginService == null)
        {
            _pluginService = Ioc.Default.GetService<PluginManager>();
        }
        
        var name = data.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
        var type = Type.GetType(name);
        if (type != null)
        {
            return (Control)Activator.CreateInstance(type)!;
        }
        
        // Try it without "View" (ex. GroupControlsControlViewModel -> GroupContentsControl)
        type = Type.GetType(name.Substring(0, name.LastIndexOf("View")));
        if (type != null && name != originalName)
        {
            var control = (Control)Activator.CreateInstance(type);
            return control;
        }
        
        if (_pluginService.ViewExists(name))
        {
            var control = (Control)Activator.CreateInstance(_pluginService.GetView(name));
            return control;
        }
        
        

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

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