using Newtonsoft.Json;
using SharedData.Models;
using System.Text;

namespace RankingApp_WebAPI.Data.Services
{
    public class RankingService
    {
        HttpClient _httpClient;

        public RankingService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        // Create
        public async Task<GameResult> AddGameResult(GameResult gameResult)
        {
            string jsonStr = JsonConvert.SerializeObject(gameResult);
            var content = new StringContent(jsonStr, Encoding.UTF8, "application/json");
            var result = await _httpClient.PostAsync("api/ranking", content);
            if (!result.IsSuccessStatusCode)
                throw new Exception("AddGameResult Failed");

            var resultContent = await result.Content.ReadAsStringAsync();
            GameResult resultOject = JsonConvert.DeserializeObject<GameResult>(resultContent);

            return resultOject;
        }

        // Read
        public async Task<List<GameResult>> GetGameResultsAsync()
        {
            var result = await _httpClient.GetAsync("api/ranking");
            if (!result.IsSuccessStatusCode)
                throw new Exception("AddGameResult Failed");

            var resultContent = await result.Content.ReadAsStringAsync();
            List<GameResult> resultObject = JsonConvert.DeserializeObject<List<GameResult>>(resultContent);

            return resultObject;
        }

        // Update
        public async Task<bool> UpdateGameResult(GameResult gameResult)
        {
            string jsonStr = JsonConvert.SerializeObject(gameResult);
            var content = new StringContent(jsonStr, Encoding.UTF8, "application/json");
            var result = await _httpClient.PutAsync("api/ranking", content);
            if (!result.IsSuccessStatusCode)
                throw new Exception("AddGameResult Failed");

            var resultContent = await result.Content.ReadAsStringAsync();
            bool resultObject = JsonConvert.DeserializeObject<bool>(resultContent);

            return resultObject;
        }

        // Delete
        public async Task<bool> DeleteGameResult(GameResult gameResult)
        {
            var result = await _httpClient.DeleteAsync($"api/ranking/{gameResult.Id}");
            if (!result.IsSuccessStatusCode)
                throw new Exception("AddGameResult Failed");

            var resultContent = await result.Content.ReadAsStringAsync();
            bool resultObject = JsonConvert.DeserializeObject<bool>(resultContent);

            return resultObject;
        }
    }
}
