using InABox.API;
using InABox.Core;
using NPOI.SS.UserModel;

namespace InABox.IPC
{
    
    
    
    public class RPCQueryHandler : RPCCommandHandler<IRPCServer,RPCQueryParameters,RPCQueryResponse> 
    {
        public override RPCQueryResponse? Execute(RPCQueryParameters? parameters)
        {
            var response = new RPCQueryResponse();

            List<Task<RPCQueryTable>> tasks = new List<Task<RPCQueryTable>>();
            foreach (var query in parameters.Queries)
            {
                var task = Task<RPCQueryTable>.Run(() =>
                {
                    var table = new RPCQueryTable() { Key = query.Key };
                    
                    // Populate the Table Here given query.filter, query.columns, query.sort 
                    
                    //if (query.Type == null)
                    //    throw new Exception("Parameters.Type is NULL!");   
                    //var servicetype = typeof(RestService<>).MakeGenericType(query.Type);
                    //var service = Activator.CreateInstance(servicetype);
                    
                    return table;
                });
                tasks.Add(task);

            }
            Task.WaitAll(tasks.ToArray());

            response.Tables = tasks.Select(x => x.Result).ToArray();
            
            return response;
        }

        public RPCQueryHandler(IRPCServer sender) : base(sender)
        {
        }
    }
}