using Newtonsoft.Json.Linq;
using System.Globalization;
using System.Net.Http;
using System.Reflection.PortableExecutable;
using System.Security.Policy;
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Net;
using Newtonsoft.Json;

namespace EVCB_OCPP.WEBAPI.Services
{
    public static class InternalHttpResultConvert
    {
        public static InternalHttpResult Convert(ObjectResult from)
        {
            InternalHttpResult result = new InternalHttpResult() { Success = false };

            try
            {
                var isSuccess = new HttpResponseMessage((HttpStatusCode)from.StatusCode).IsSuccessStatusCode;
                if (isSuccess)
                {
                    JObject jo = JObject.Parse(JsonConvert.SerializeObject(from.Value));

                    if (jo.ContainsKey("SerialNo"))
                    {
                        string _SerialNo = jo["SerialNo"].Value<string>();
                        result.SerialNo = _SerialNo;
                    }

                    if (jo.ContainsKey("Message"))
                    {
                        string _Message = jo["Message"].Value<string>();
                        result.Message = _Message;
                    }

                }
                else
                {
                    JObject jo = JObject.Parse(JsonConvert.SerializeObject(from.Value));

                    if (jo.ContainsKey("Message"))
                    {
                        string _Message = jo["Message"].Value<string>();
                        result.Message = _Message;
                    }

                    if (jo.ContainsKey("Code"))
                    {
                        int _ErrorCode = jo["Code"].Value<int>();
                        result.ErrorCode = _ErrorCode;
                    }
                }

                result.Status = (HttpStatusCode)from.StatusCode;
                result.Success = isSuccess;
                //result.Message = (string)from.Value?.ToString();
                //result.Exception = from;//.Exception;


            }
            catch (Exception ex)
            {
                result.Exception = ex;
            }

            return result;
        }
    }
}
