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

namespace Rest.Net
{
    public static class HttpListenerResponseExtensions
    {
        public static HttpListenerResponse WithText(this HttpListenerResponse response, string text)
        {
            response.ContentType = "text/plain";

            var bytes = Encoding.UTF8.GetBytes(text);
            response.OutputStream.Write(bytes, 0, bytes.Length);

            return response;
        }

        public static HttpListenerResponse WithJson(this HttpListenerResponse response, object obj)
        {
            response.ContentType = "application/json";

            var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj));
            response.OutputStream.Write(bytes, 0, bytes.Length);

            return response;
        }

        public static HttpListenerResponse WithFile(this HttpListenerResponse response, string filePath)
        {
            response.ContentType = "application/octet-stream";
            response.Headers.Add("Content-Deposition", $@"attachment; filename=""{Path.GetFileName(filePath)}""");
            response.SendChunked = true;

            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            using (var responseStream = response.OutputStream)
                fileStream.CopyTo(responseStream);

            return response;
        }

        public static HttpListenerResponse WithStatus(this HttpListenerResponse response, HttpStatusCode status)
        {
            try
            {
                response.StatusCode = (int)status;
                return response;
            }
            catch
            {
                return response;
            }
        }
    }
}
