using Apewer.Web;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Apewer.AspNetBridge
{

    /// <summary></summary>
    public abstract class ApiController
    {

        /// <summary></summary>
        public ApiRequest Request { get; internal set; }

        /// <summary></summary>
        public ApiResponse Response { get; internal set; }

        /// <summary></summary>
        protected virtual IHttpActionResult Bytes(byte[] bytes, string contentType = "application/octet-stream", string attachmentName = null)
        {
            var har = new HttpActionResult();
            har.Bytes = bytes;
            har.ContentType = contentType;
            har.Attachment = attachmentName;
            return har;
        }

        /// <summary></summary>
        protected virtual IHttpActionResult Text(string text, string contentType = "text/plain")
        {
            var har = new HttpActionResult();
            har.Bytes = text.Bytes();
            har.ContentType = contentType;
            return har;
        }

        /// <summary></summary>
        protected virtual IHttpActionResult Json<T>(T content)
        {
            var json = Apewer.Json.From(content, false, -1, true);
            var text = json == null ? "" : json.ToString();
            return Bytes(text.Bytes(), "application/json");
        }

        /// <summary></summary>
        protected static string MapPath(string relativePath)
        {
            var root = RuntimeUtility.ApplicationPath;
            var path = root;
            if (relativePath.NotEmpty())
            {
                var split = relativePath.Split('/');
                foreach (var seg in split)
                {
                    if (seg.IsEmpty()) continue;
                    if (seg == "~") path = root;
                    path = Path.Combine(path, seg);
                }
            }
            return path;
        }

    }

}