using System.Reflection;
using System.Text.RegularExpressions;
using Hawkeye.VisionBuilder.Workflow.Configuration;
using Hawkeye.VisionBuilder.Workflow.Links;
using Hawkeye.VisionBuilder.Workflow.Operations.Attributes;
using Ninject;
using Ninject.Infrastructure.Language;

namespace Hawkeye.VisionBuilder.Workflow;

public class OperationDiscoveryService
{

    private readonly WorkflowList _workflowList;
    private readonly StandardKernel _kernel;

    public OperationDiscoveryService( WorkflowList workflowList)
    {

        _workflowList = workflowList;
        _kernel = new StandardKernel();

        _kernel.Bind<WorkflowList>().ToConstant(workflowList);

    }



    public List<OperationDescription> DiscoverOperations()
    {
        return this.GetType().Assembly.GetTypes()
            .Where(x => x.IsSubclassOf(typeof(BaseOperation))&&!x.HasAttribute(typeof(IgnoreOperationAttribute)))
            .Where(x=>x.Name!=nameof(NoOrigin))
            .Select(x=>new OperationDescription()
            {
                Name = BaseOperation.MakeOperationName(x.Name),
                Category = GetCategory(x),
                Type = x
            }).ToList();
    }

    private string GetCategory(Type t)
    {
        var category=t.GetCustomAttribute(typeof(Category));
        if (category!=null)
        {
            return (category as Category).Name;
        }

        return "General";
    }

    public BaseOperation CreateInstance(Type type)
    {
        return (BaseOperation)_kernel.Get(type);
    }
    
}