using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace nuget_cli
{
    internal class PushCommand
    {
        static internal async Task<PushReport> RunAsync(string pkg, string source, string apikey)
        {
            FileInfo fi = new FileInfo(pkg);
            var report = new PushReport
            {
                PkgName = fi.Name
            };
            if (!fi.Exists)
            {
                report.Message = "Le fichier n'existe pas";
                return report;
            }

            try
            {
                var wrqueryHandler = new UploadFilesToServerUsingWebRequest();
                await wrqueryHandler.UploadFilesToServerAsync(report, new Uri(source), fi, apikey);
#if FAILS
                var hcqueryHandler = new HttpClientServerQueryHandler();
                await hcqueryHandler.UploadFilesToServerAsync(report, new Uri(source), fi, apikey);
#endif

            }
            catch (WebException ex)
            {
                await Console.Error.WriteLineAsync(ex.Message);
                report.StatusCode = ex.Status.ToString();
                report.OK = false;
                using (Stream respStream = ex.Response.GetResponseStream())
                {
                    StreamReader sr = new StreamReader(respStream);
                    string json = sr.ReadToEnd();
                    var res = JsonConvert.DeserializeObject<NugetdErrorMessage>(json);
                    // ecode == 1 => package already present server side.
                    report.AlreadyPresent = res.ecode == 1;
                    report.Message = res.msg;
                }
            }
            catch (Exception ex)
            {
                report.Message = ex.Message;
                report.StackTrace = ex.StackTrace;
                await Console.Error.WriteLineAsync(ex.Message);
                throw;
            }
            report.Executed = true;
            return report;
        }
    }
}