using IVM.Models;
using Newtonsoft.Json;
using System.Xml;
using Kendo.Mvc.UI;
using IVM.Models.HttpResponses;
using Microsoft.AspNetCore.Mvc.ViewFeatures;

namespace IVM.Services.IVMAPIService
{
    public partial class IvmApiService
    {
        public enum Method
        { GET = 0,
          POST = 1,
          PUT = 2,
          DElETE = 3,
          HEAD = 4,
          OPTIONS = 5,
          PATCH = 6,
          MERGE = 7,
          COPY = 8 }

        private Dictionary<string, XmlElement?> Pager = new Dictionary<string, XmlElement?>();

        private string JsonString;

        public XmlElement? Pagination { get; private set; }

        public List<Address> AddressSrchResult { get; private set; }
        public List<List<Address>> addresses { get; private set; }
        //public webClient WebClient { get; private set; }
        public static int? AddressTopId { get; set; }

        public IvmApiService(string token, string baseUrl)
        {
            //WebClient = new webClient(token, baseUrl);
            //Assembly assembly = Assembly.LoadFrom("bin\\debug\\net6.0\\IVM.dll");
            //Type type = assembly.GetType("IVM.Models.AddressTypes");
            //var listType = typeof(List<>).MakeGenericType(type);
            //var list = Activator.CreateInstance(listType);
            JsonString = "{'Data, 'Array'}";

            string? restResponse = MakeRequest("AddressType", ref Pager, Method.GET);
            AddressTypes.addressTypes = JsonConvert.DeserializeObject <List<AddressTypes>>(restResponse);

            restResponse = MakeRequest("Country", ref Pager, Method.GET);
            if (Pager["Country"] != null)
              restResponse = MakeRequest($"Country?page=1&pageSize={Pager["Country"]["totalRecords"].InnerText}", ref Pager, Method.GET);
            CountryModel.Countries = JsonConvert.DeserializeObject<List<CountryModel>>(restResponse);

            restResponse = MakeRequest("StateProvince", ref Pager, Method.GET);
            if (Pager["StateProvince"] != null)
              restResponse = MakeRequest($"StateProvince?page=1&pageSize={Pager["StateProvince"]["totalRecords"].InnerText}", ref Pager, Method.GET);
            StatesProvinces.StateProvince = JsonConvert.DeserializeObject<List<StatesProvinces>>(restResponse);
        }

        internal T GetRelatedRecordByID<T>(string endPoint)
        { string? restResponse = MakeRequest(endPoint, ref Pager);
          T? response = JsonConvert.DeserializeObject<T>(restResponse);
          return response;
        }
        internal T GetRelatedTableAddress<T>(string endPoint)
        {
            object response = null;
            string? restResponse = MakeRequest(endPoint, ref Pager);

            if (restResponse != null)
                response = JsonConvert.DeserializeObject<T>(restResponse) ;
            T retval = (T)response;
            return retval;
        }

        internal ViewDataDictionary GetTableCounts(ViewDataDictionary retval, string[] objects)
        {
            object result = null;
            int count = 0;

            foreach (string obj in objects)
            {
                switch (obj)
                {
                    case "Machines":
                        count = GetRelatedTableAddress<AddressMachine>($"Address/{obj}?id={AddressTopId}&activeStatus=Active").machineAddresses.Count();
                        break;
                    case "Vendors":
                        count = GetRelatedTableAddress<AddressVendor>($"Address/{obj}?id={AddressTopId}&activeStatus=Active").vendorAddresses.Count();
                        break;
                    case "Clients":
                        count = GetRelatedTableAddress<AddressClient>($"Address/{obj}?id={AddressTopId}&activeStatus=Active").clientAddresses.Count();
                        break;
                    case "Locations":
                        count = GetRelatedTableAddress<AddressLocation>($"Address/{obj}?id={AddressTopId}&activeStatus=Active").locationAddresses.Count();
                        break;
                }
                retval.Add(obj, count);
            }
            return retval;
        }

        //internal List<ProductModel> GetProducts()
        //{
        //    string? restResponse = MakeRequest("Product?activeStatus=Active", ref Pager, Method.GET);
        //    string pageSize = Pager["Product"] != null ? Pager["Product"]["totalRecords"].InnerText : "50";
        //    restResponse = MakeRequest($"Product?activeStatus=Active&page=1&pageSize={pageSize}", ref Pager, Method.GET);
        //    var Product = JsonConvert.DeserializeObject<List<ProductModel>>(restResponse);
        //    return Product;
        //}

        private string? MakeRequest(string endpoint, JsonHelper? jsonHelp, Method method = Method.GET)
        {
            string? responseText = null;
        //    JsonHelper jsHelp = new(WebClient.SendRequest(method.ToString(), endpoint, jsonHelp.JsonString)) { AllRecords = endpoint.Contains("&pageSize") };
        //    responseText = jsHelp.GetRequest(endpoint);
            return responseText;
        }

        public string? MakeRequest(string endpoint, ref Dictionary<string, XmlElement?> pager, Method method = Method.GET)
        {
            string? responseText = null;
        //    JsonHelper jsHelp = null;
        //    switch (method)
        //    { case Method.GET:
        //        jsHelp = new(WebClient.SendRequest(method.ToString(), endpoint, JsonString)) { AllRecords = endpoint.Contains("&pageSize") };
        //        responseText = jsHelp.GetDataArray(jsHelp.GetRequest(endpoint));

        //        if (pager == null || pager.ContainsKey(endpoint.Split('?')[0]))
        //        {
        //          if (pager == null)
        //            pager = new Dictionary<string, XmlElement?>();
        //          if (pager.ContainsKey(endpoint.Split('?')[0]))
        //            pager.Remove(endpoint.Split('?')[0]);
        //        }

        //        pager.Add(endpoint.Split('?')[0], jsHelp.Pagination);
        //        break;
        //      case Method.DElETE:
        //        jsHelp = new(WebClient.SendDelete(method.ToString(), endpoint));
        //        responseText = jsHelp.DeleteData(endpoint);
        //        break;
        //      case Method.PUT:
        //        jsHelp = new(WebClient.SetRequest(method.ToString(), endpoint, JsonString));
        //        responseText = jsHelp.PutDataArray(endpoint);
        //        break;
        //      case Method.POST:
        //      break; }

            return responseText;
        }
    }
}
