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

namespace isn
{
    public static class PushCommand
    {
        static public PushReport Run(string pkg, string source, string apikey)
        {
            if (source == null) source = Program.Settings.DefaultSourceKey;
            if (source == null) throw new InvalidOperationException("source is null");
            if (Program.Settings.Sources.Values.Any(s=>s.Alias==source))
                source = Program.Settings.Sources.First(s=>s.Value.Alias==source).Key;
            if (source==null) throw new InvalidOperationException("source is invalid");

            var resources = SourceHelpers.GetServerResources(source);
            if (resources.Resources == null)
            throw new InvalidOperationException("source gave no resource");
            if (!resources.Resources.Any(res => res.Type == "PackagePublish/2.0.0"))
                throw new InvalidOperationException("Source won't serve the expected push command");
            var pubRes = resources.Resources.First(res => res.Type == "PackagePublish/2.0.0");
            FileInfo fi = new FileInfo(pkg);
            if (!fi.Exists)
            {
                var report = new PushReport
                {
                    PkgName = fi.Name,
                    Message = "Le fichier n'existe pas"
                };
                return report;
            }
            using (var client = new HttpClient())
            try
            {
                Console.WriteLine("Connecting to "+ pubRes.Id);
                return  client.UploadFilesToServer(new Uri(pubRes.Id), fi, apikey);
            }
            catch (HttpRequestException hrex)
            {
                var report = new PushReport
                {
                    PkgName = fi.Name,
                    Message = "HttpRequest: " + hrex.Message,
                    StackTrace = hrex.StackTrace,
                    StatusCode = hrex.HResult.ToString()
                };
                Console.Error.WriteLine(hrex.Message);
                return report;
            }
            catch (Exception ex)
            {
                var report = new PushReport
                {
                    PkgName = fi.Name,
                    Message = ex.Message,
                    StackTrace = ex.StackTrace
                };
                Console.Error.WriteLine(ex.Message);
                return report;
            }
        }
    }
}