using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace isn
{
    public static class UploadFilesToServerUsingHttpClient
    {
        public static PushReport UploadFilesToServer(this HttpClient client, Uri uri, FileInfo fi,
      string apikey)
        {
            return UploadFilesToServerAsync(client, uri, fi, apikey).Result;
        }

        public static async Task<PushReport> UploadFilesToServerAsync(this HttpClient client, Uri uri, FileInfo fi,
       string apikey)
        {

            client.DefaultRequestHeaders.Add("X-NuGet-Client-Version", Constants.ClientVersion);
            client.DefaultRequestHeaders.Add("X-NuGet-ApiKey", apikey);

            using (var multipartFormDataContent = new MultipartFormDataContent())
            {
                multipartFormDataContent.Add(new ByteArrayContent(File.ReadAllBytes(fi.FullName)),
                    '"' + "File" + '"',
                    '"' + fi.Name + '"');

                var result = await client.PutAsync(uri, multipartFormDataContent);
                if (result.IsSuccessStatusCode) return
                new PushReport() { 
                    KO = JsonConvert.DeserializeObject<APIKO>(await result.Content.ReadAsStringAsync()) 
                };
                else
                return new PushReport() { 
                    OK = true
                };
            }
        }
    }
}