using AutoCat.Model.Requests;
using AutoCatCore.Model;
using AutoCatCore.Model.Requests;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace AutoCat.Utils
{
	public class Api
	{
		private static HttpClient client;

		static Api()
		{
			client = new HttpClient();
			client.BaseAddress = new Uri("https://vps.aliencat.pro:8443");
		}

		private static JToken GetDataOrThrow(string response)
		{
			JObject jResp = JObject.Parse(response);
			if ((bool)jResp["success"] == true)
			{
				return jResp["data"];
			}
			else
			{
				throw new Exception((string)jResp["error"]);
			}
		}

		private static T GetDataOrThrow<T>(string response)
		{
			return GetDataOrThrow(response).ToObject<T>();
		}

		public static void SetAccessToken(string token)
		{
			client.DefaultRequestHeaders.Remove("Authorization");
			client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
		}

		public static async Task<User> Login(string email, string password)
		{
			var credentials = new Credentials() { Email = email, Password = password };
			var json = JsonConvert.SerializeObject(credentials);
			var content = new StringContent(json, Encoding.UTF8, "application/json");
			var response = await client.PostAsync("user/login", content);
			var respStr = await response.Content.ReadAsStringAsync();
			var result = GetDataOrThrow<User>(respStr);
			SetAccessToken(result.Token);
			return result;
		}

		public static async Task<PagedResponse<Vehicle>> GetVehicles()
		{
			var response = await client.GetAsync("vehicles");
			var respStr = await response.Content.ReadAsStringAsync();
			return GetDataOrThrow<PagedResponse<Vehicle>>(respStr);
		}
	}
}
