using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;

namespace Kynareth.Helpers;

public class StreamResult : ActionResult, IStatusCodeActionResult, IActionResult
{
	public string ContentType { get; set; }
	public int? StatusCode { get; set; }
	public Stream Value { get; set; }

	public StreamResult(Stream data)
	{
		Value = data;
	}

	public override void ExecuteResult(ActionContext context)
		=> ExecuteResultAsync(context).ConfigureAwait(false);

	public override async Task ExecuteResultAsync(ActionContext context)
	{
		if (context == null)
		{
			throw new ArgumentNullException(nameof(context));
		}

		var response = context.HttpContext.Response;

		response.StatusCode = StatusCode ?? 200;

		response.ContentType = !string.IsNullOrEmpty(ContentType)
			? ContentType
			: "image/png";

		await Value.CopyToAsync(response.Body);

		await Value.FlushAsync();

		await Value.DisposeAsync();


		context.HttpContext.Response.RegisterForDisposeAsync(Value);

		GC.Collect();
	}
}