﻿using Slipspace.Sharp.Common.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.ExceptionHandling;

namespace Slipspace.Sharp.WebApi
{
    public class SlipspaceExceptionLogger : ExceptionLogger
    {
        public override void Log(ExceptionLoggerContext context)
        {
            SendError(context);
        }

        public override Task LogAsync(ExceptionLoggerContext context, System.Threading.CancellationToken cancellationToken)
        {
            return Task.Run(() =>
                {
                    SendError(context);
                });
        }

        private void SendError(ExceptionLoggerContext context)
        {
            if (context.RequestContext != null && context.RequestContext.Principal != null && context.RequestContext.Principal.Identity.IsAuthenticated)
            {
                new SlipspaceClient()
                    .SetUser(new User { Uuid = context.RequestContext.Principal.Identity.Name })
                    .SendInBackground(context);
            }
            else
            {
                new SlipspaceClient()
                    .SendInBackground(context);
            }
        }
    }
}
