using IntegrationS4.RDnL.Services;
using RnD.API;
using RnD.Attributes;
using RnD.Messages.Client;
using RnD.Model;

namespace IntegrationS4.RDnL.CustomActions
{
    [CustomFunction("IntegrationS4CustomAction", RnD.Common.Enums.CustomFunctionType.CustomAction)]
    public class IntegrationS4CustomAction : AdvancedCustomFunction, ICustomAction<ICustomContext>
    {
        public IntegrationS4CustomAction(IAPI aAPI) : base(aAPI) { }

        public void Execute(ICustomContext aContext)
        {
            var specification = aContext.Entity as ISpecification;
            if (specification is null)
            {
                Log.Error("Specification for sending is null");
                return;
            }
            var requiredStatus = 1000021; //Status;
            if (specification.Status != requiredStatus)
            {
                Log.Error("The status of the specification has an invalid value for the transition");
                return;
            }
            dynamic request = IntegrationS4Service.ExportS4(specification);
            var userId = (decimal)aContext.Event.UserName;
            var user = API.User.GetUser(userId).UserName;
            var connectionName = API.CustomizationSession.ConnectionName;
            var browserGuid = API.CustomizationSession.BrowserGuid;
            var notificationClient = new NotificationClient();
            MessageService.SendMessage(request.Message, request.Type, notificationClient, user, connectionName, browserGuid);
            Log.Info(request.Message);
        }
    }
}