using Pilz.Data;
using Pilz.Extensions.Reflection;
using Pilz.Net.Extensions;
using System.Diagnostics;
using System.Net;

namespace Pilz.Net.Api.Server;

public abstract class BaseItemHandler<TEntity, TUpdateMsg>(IApiServer server)
    : BaseHandler<TEntity, TUpdateMsg>(server)
    where TEntity : class, IDataObject
    where TUpdateMsg : ApiMessage
{
    protected virtual bool RegisterGetAll => true;
    protected virtual bool RegisterPost => true;

    public override void Initialize(IApiServer server)
    {
        base.Initialize(server);
        var t = GetType();
        if (RegisterGetAll)
            server.RegisterHandler(t.GetMethod(nameof(GetAll))!.CreateDelegate(this), new(Route, "GET"), Debugger.IsAttached);
        if (RegisterPost)
            server.RegisterHandler(t.GetMethod(nameof(Post))!.CreateDelegate(this), new(Route, "POST"), Debugger.IsAttached);
    }

    public virtual ApiResult GetAll()
    {
        return server.Manager.Get<TEntity>().ToList().Select(ToClient).ToItemsResult();
    }

    public virtual ApiResult Post(TUpdateMsg msg)
    {
        var entity = CreateNewEntity(msg);
        if (UpdateEntity(entity, msg) is ApiResult result)
            return result;
        server.Manager.Save(entity, true);
        return ToClient(entity).ToItemResult(HttpStatusCode.Created);
    }
}
