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; using System.Net.Http.Headers; using System; 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 { var url = urlBase + ressource; var request = new HttpRequestMessage(HttpMethod.Post, url); request.Headers.Accept.Clear(); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); var jsonObject = JsonConvert.SerializeObject(answer); request.Content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); var response = await httpClient.SendAsync(request, CancellationToken.None); 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; } } } }