using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;

namespace Grand.Web.Common.Controllers;

public static class ControllerExtensions
{
    public static async Task<string> RenderPartialViewToString<TModel>(this Controller controller, string viewName,
        TModel model, bool partial = false)
    {
        if (string.IsNullOrEmpty(viewName)) viewName = controller.ControllerContext.ActionDescriptor.ActionName;

        controller.ViewData.Model = model;

        await using var writer = new StringWriter();
        IViewEngine viewEngine =
            controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
        if (viewEngine == null) return writer.GetStringBuilder().ToString();
        var viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);

        if (viewResult.Success == false) return $"A view with the name {viewName} could not be found";

        ViewContext viewContext = new(
            controller.ControllerContext,
            viewResult.View,
            controller.ViewData,
            controller.TempData,
            writer,
            new HtmlHelperOptions()
        );

        await viewResult.View.RenderAsync(viewContext);

        return writer.GetStringBuilder().ToString();
    }
}