using DamageAssesment.Api.Responses.Interfaces;
using DamageAssesment.Api.Responses.Models;
using Newtonsoft.Json;

namespace DamageAssesment.Api.Responses.Services
{
    public class AttachmentServiceProvider : ServiceProviderBase, IAttachmentServiceProvider
    {
        public AttachmentServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger<AttachmentServiceProvider> logger) : base(configuration, httpUtil, logger, configuration.GetValue<string>("RessourceSettings:Attachment"), configuration.GetValue<string>("EndPointSettings:AttachmentUrlBase"))
        {
        }

        public async Task<List<Attachment>> getAttachmentsAsync()
        {
            try
            {
                var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null);
                var attachments = JsonConvert.DeserializeObject<List<Attachment>>(responseJsonString);

                if (attachments == null || !attachments.Any())
                    return new List<Attachment>();
                else return attachments;
            }
            catch (Exception ex)
            {
                logger?.LogError($"Exception Found : {ex.Message} - Ref: AttachmentServiceProvider.getAttachmentsAsync()");
                return new List<Attachment>();
            }
        }

        public async Task<IEnumerable<Attachment>> PostAttachmentsAsync(AttachmentInfo attachmentInfo)
        {
            try
            {
                var requestJsonString = JsonConvert.SerializeObject(attachmentInfo);
                var responseJsonString = await httpUtil.SendAsync(HttpMethod.Post, url, requestJsonString);
                var attachments = JsonConvert.DeserializeObject<IEnumerable<Attachment>>(responseJsonString);

                if (attachments == null)
                {
                    logger?.LogError($"Attachments cannot be added - Ref: AttachmentServiceProvider.PostAttachmentsAsync()");
                    return null;
                }
                else return attachments;
            }
            catch (Exception ex)
            {
                logger?.LogError($"Exception Found : {ex.Message} - Ref: AttachmentServiceProvider.PostAttachmentsAsync()");
                return null;
            }
        }

    }

}