﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace ncore.Http
{
    public static class Http
    {
        static HttpClient client = new HttpClient() { Timeout = new TimeSpan(0, 0, 10) };
        public static async Task<string> Request(string type, string apiUrl, string requestPath, string requestBody)
        {
            string finalUrl = "";
            var Ty = type.ToUpper();

            switch (Ty)
            {
                case "GET":
                    {
                        finalUrl = string.Format("{0}{1}?{2}", apiUrl, requestPath, WebUtility.UrlEncode(requestBody));
                        var response = await client.GetAsync(finalUrl);
                        var StatusCode = response.EnsureSuccessStatusCode();
                        return await response.Content.ReadAsStringAsync();
                    }

                case "POST":
                    {
                        finalUrl = string.Format("{0}{1}", apiUrl, requestPath);
                        var response = await client.PostAsync(finalUrl, new StringContent(requestBody, Encoding.UTF8, "application/x-www-form-urlencoded"));
                        var StatusCode = response.EnsureSuccessStatusCode();
                        return await response.Content.ReadAsStringAsync();
                    }
            }

            throw new Exception(string.Format("Invalid request type! {0}", Ty));
        }
    }
}
