using System;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Text;
using Newtonsoft.Json;

namespace MEU.API.MiddleWare
{
    public class CustomModelBinder: IModelBinder 
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            
            var request = bindingContext.HttpContext.Request;

            using (var reader = new StreamReader(request.Body, Encoding.UTF8))
            {
                try
                {
                    var bodyString = reader.ReadToEnd();
                    var resultObject = JsonConvert.DeserializeObject<object>(bodyString);
                    RequestParams.setParam(bindingContext.FieldName, resultObject);
                    var result = JsonConvert.DeserializeObject(bodyString, bindingContext.ModelType);
                    bindingContext.Result = ModelBindingResult.Success(result);
                }
                catch (Exception ex)
                {
                }
              
            }

            return Task.CompletedTask;
        }
    }
}
