using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using isn.Abstract;
using Newtonsoft.Json;

namespace isn
{
    public static class SourceHelpers
    {
        public static async Task<ApiIndexViewModel> GetServerResourcesAsync(string url)
        {
            HttpClient client = new HttpClient();
            // var json = await client.GetStringAsync(new System.Uri(url));
            try 
            {
            var response = await client.GetStringAsync(url);
           // var json = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<ApiIndexViewModel>(response);

            }
            catch(Exception ex)
            {
                throw;
            }
        }

        public static async Task<ApiIndexViewModel> GetServerResourcesUsingWebRequestAsync(string url)
        {
            ApiIndexViewModel viewModel=null;
            var uri = new Uri(url);

             HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
             httpWebRequest.Method = "GET";
            httpWebRequest.AllowAutoRedirect = false;
            try{

            using (var resp = await httpWebRequest.GetResponseAsync())
            {
                using (var stream = resp.GetResponseStream())
                {
                    using (var reader = new StreamReader(stream))
                    {
                        var json = await reader.ReadToEndAsync();
                        Console.Write("got json : "+json);
                        viewModel = JsonConvert.DeserializeObject<ApiIndexViewModel>(json);
                        
                    }
                }

            }
            }
            catch(Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
            }
            return viewModel;
        }
    }
}