using DeviceRepair.Utils;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;

namespace DeviceRepair.Api.Models
{
    public class GzipCompressedResult : IHttpActionResult
    {
        private readonly string _content;
        private readonly HttpRequestMessage _request;

        public GzipCompressedResult(string content, HttpRequestMessage request)
        {
            _content = content;
            _request = request;
        }

        public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            var contentBytes = Encoding.UTF8.GetBytes(_content);

            using (var outputStream = new MemoryStream())
            {
                using (var gzipStream = new GZipStream(outputStream, CompressionMode.Compress))
                {
                    await gzipStream.WriteAsync(contentBytes, 0, contentBytes.Length, cancellationToken);
                }

                response.Content = new ByteArrayContent(outputStream.ToArray());
                response.Content = new StringContent(System.Convert.ToBase64String(outputStream.ToArray()), Encoding.UTF8, "text/html");
                //response.Content.Headers.ContentEncoding.Add("gzip");
                //response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                //response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            }

            response.RequestMessage = _request;
            return response;
        }
    }
}