using DamageAssesment.Api.SurveyResponses.Bases; using DamageAssesment.Api.SurveyResponses.Db; using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; using Newtonsoft.Json; using System.Data.Common; using System.Security.Cryptography; using System.Text.Json.Nodes; using System.Text; namespace DamageAssesment.Api.SurveyResponses.Providers { public class AnswerServiceProvider : ServiceProviderBase, IAnswerServiceProvider { public AnswerServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger, IRegionServiceProvider regionServiceProvider, ILocationServiceProvider locationServiceProvider) : base(configuration, httpClient, logger, "/api/Answers", configuration.GetValue("EndPointSettings:AnswerUrlBase")) { } public async Task> getAnswersAsync() { try { httpClient.BaseAddress = new Uri(urlBase); var response = await httpClient.GetAsync(ressource); response.EnsureSuccessStatusCode(); var responseString = await response.Content.ReadAsStringAsync(); var answers = JsonConvert.DeserializeObject>(responseString); if (answers == null || !answers.Any()) return null; else return answers; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.getAnswersAsync()"); return null; } } public async Task> GetAnswersByResponseIdAsync(int responseId) { try { httpClient.BaseAddress = new Uri(urlBase); var response = await httpClient.GetAsync("/api/AnswersByResponse/"+ responseId); response.EnsureSuccessStatusCode(); var responseString = await response.Content.ReadAsStringAsync(); var answers = JsonConvert.DeserializeObject>(responseString); if (answers == null || !answers.Any()) return null; else return answers; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.GetAnswersByResponseId()"); return null; } } public async Task PostAnswersAsync(Answer answer) { try { httpClient.BaseAddress = new Uri(urlBase); var jsonObject = JsonConvert.SerializeObject(answer); var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); var response = await httpClient.PostAsync(ressource,content); response.EnsureSuccessStatusCode(); var responseString = await response.Content.ReadAsStringAsync(); var answers = JsonConvert.DeserializeObject(responseString); if (answers == null) { logger?.LogError($"Answer cannot be added - Ref: AnswerServiceProvider.PostAnswersAsync()"); return null; } else return answers; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.PostAnswersAsync()"); return null; } } } }