using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Console = HyperCube.Utils.AdvConsole;
using HyperCube.Models;

namespace HyperCube
{
    public class Post
    {
        public static async Task<string> PostRequestAsync(Blockchain bc, string json)
        {
            if (bc != null)
            {
                Console.WriteLine($"json req {json} len {json.Length}");
                string url = $"http://{bc.url}:{bc.port}";
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "POST";
                httpWebRequest.Accept = "application/json";
                Console.WriteLine($"PostRequestAsync {url}");

                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(json);
                }

                HttpWebResponse response = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        //Console.WriteLine(reader.ReadToEnd());

                        var result = reader.ReadLine();
                        Console.WriteLine($"json result {result} len {result.Length}");
                        response.Close();
                        return result;
                    }
                }                
            }
            return "null";
        }
    }
}
