using System.Net;
using System.Net.Http;
using System.Web.Http;
using iiie.Logs.DBO;

namespace iiie.WebApiUtils.BusinessManager
{
    /// <summary>
    /// Handle business manager results
    /// </summary>
    /// <typeparam name="T">Data type</typeparam>
    public class BMRHandler<T>
    {
        /// <summary>
        /// Converts ResultStatus codes to HttpStatusCodes codes
        /// </summary>
        /// <param name="status">The status code</param>
        /// <returns>The http code</returns>
        public static HttpStatusCode ResultStatusToHttp(ResultStatus status)
        {
            if (status == ResultStatus.LoginError)
                return HttpStatusCode.Unauthorized;
            if (status == ResultStatus.PermissionError)
                return HttpStatusCode.Forbidden;
            if (status == ResultStatus.InputError)
                return HttpStatusCode.BadRequest;
            if (status == ResultStatus.NotFound)
                return HttpStatusCode.NotFound;
            return HttpStatusCode.InternalServerError;
        }

        /// <summary>
        /// Returns a string corresponding to the error
        /// </summary>
        /// <param name="result">The result of the operation</param>
        /// <returns>The error string</returns>
        public static string OpResultToString(OpResult<T> result)
        {
            if (result.PublicDetails != null)
                return result.PublicDetails;

            if (result.Status == ResultStatus.LoginError)
                return "Bad username/password";
            if (result.Status == ResultStatus.PermissionError)
                return "You don\'t have the permission to do this action";
            if (result.Status == ResultStatus.InputError)
                return "Invalid data was provided";
            if (result.Status == ResultStatus.NotFound)
                return "Ressource not found";

            return "Internal error";
        }

        /// <summary>
        /// Handle business manager results
        /// </summary>
        /// <param name="result">The result to handle</param>
        /// <param name="request">The request to handle</param>
        /// <returns>The data to return to the user</returns>
        public static T Handle(OpResult<T> result, HttpRequestMessage request)
        {
            if (result.Status == ResultStatus.Success)
                return result.Data;
            var msg = request.CreateErrorResponse(ResultStatusToHttp(result.Status), OpResultToString(result));
            throw new HttpResponseException(msg);
        }
    }
}
