using C4IT.DataHistoryProvider;
using C4IT.FASD.Base;
using C4IT.Logging;
using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using static C4IT.Logging.cLogManager;

namespace F4SDwebService.Controllers
{
    public class WritePropertyController : ApiController
    {
        [HttpPost]
        [Route("api/WriteProperty")]
        public async Task<IHttpActionResult> Put([FromBody] cF4SDWriteParameters jsonRequest)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }

            var requestInfo = new cF4sdWebRequestInfo("WriteProperty", jsonRequest.id.ToString(), cAuthentication.GetUserInfo(ActionContext));
            if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceStart(0, requestInfo.requestName, requestInfo.id, requestInfo.created); }

            var apiError = 0;

            try
            {
                if (await WebApiApplication.Collector.WritePropertyAsync(jsonRequest, requestInfo, CancellationToken.None))
                    return Ok();
                apiError = -1;
            }
            catch (Exception E)
            {
                apiError = E.HResult;
                LogException(E);
            }
            finally
            {
                if (WebApiApplication.Debug_apiTiming) WebApiApplication.SaveApiTimingEntry(requestInfo.requestName, requestInfo.id, requestInfo.created, apiError);
                if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceEnd(0, requestInfo.requestName, requestInfo.id, requestInfo.created, requestInfo.created, ErrorCode: apiError); }
                if (CM != null) LogMethodEnd(CM);
            }

            return BadRequest();
        }
    }
}