using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Text;
using System.IO;
using System.Web.Mvc;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using Learn_CSS.Model.Entities;

namespace Learn_CSS.APP.Web.Models.ModelBinders
{
    public class ValidateEntityBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            return Bind(controllerContext, bindingContext);
        }

        private ValidateEntity Bind(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var request = controllerContext.RequestContext.HttpContext.Request;
            var stream = request.InputStream;
            stream.Position = 0;

            string jsonText = "";

            StringBuilder stringBuilder = new StringBuilder();
            using (StreamReader reader = new StreamReader(stream))
            {
                jsonText = reader.ReadToEnd();
            }


            var json = (JObject)JsonConvert.DeserializeObject(jsonText);


            return new ValidateEntity()
            {
                ID = json["ID"].Value<int>(),
                Elements = json["Elements"]
            };
        }
    }
}