﻿using CmsWeb.Common.Extensions;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using UtilityExtensions;

namespace CmsWeb.Common.Web
{
    public class ContentWithStatusResult : ActionResult
    {
        public string Content { get; set; }
        public string ContentType { get; set; }
        public HttpStatusCode ResponseCode { get; set; } = HttpStatusCode.OK;

        public ContentWithStatusResult() : base() { }
        public ContentWithStatusResult(object content, string contentType, HttpStatusCode responseCode) : this()
        {
            if (content is string)
            {
                Content = (string)content;
            }
            else
            {
                Content = (contentType.Contains("json", ignoreCase: true) ? content?.ToJSON() : content?.ToString()) ?? "";
            }
            ContentType = contentType;
            ResponseCode = responseCode;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var Response = context.HttpContext.Response;
            Response.Clear();
            Response.StatusCode = (int)ResponseCode;
            Response.ContentType = ContentType ?? "text/plain";
            Response.Write(Content);
            Response.Flush();
            Response.Close();
        }
    }
}
