using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using RecruitmentTesting.Api.Models;

namespace RecruitmentTesting.Api.Client
{
    /// <summary>
    /// The following class shows the simplest possible sample. For a more advanced sample, check Program.cs and ApiWrapper.cs.
    /// </summary>
    public static class HelloWorld
    {
        public static void Run(string email, string apiPassword)
        {
            HttpClient client = Authorize(email, apiPassword);

            foreach (Test test in GetTests(client))
                Console.WriteLine($"Test: Id: {test.Id}, Name: {test.Name}");
        }

        static HttpClient Authorize(string email, string apiPassword)
        {
            // Create HttpClient
            HttpClient client = new HttpClient()
            {
                BaseAddress = new Uri("https://testdome.com/api/v1/")
            };
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Get token
            FormUrlEncodedContent content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", email),
                new KeyValuePair<string, string>("password", apiPassword)
            });
            HttpResponseMessage response = client.PostAsync("token", content).Result;
            string result = response.Content.ReadAsStringAsync().Result;
            string accessToken = JObject.Parse(result)["access_token"].ToString();

            // Set authorization header.
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            return client;
        }

        static IEnumerable<Test> GetTests(HttpClient client)
        {
            HttpResponseMessage response = client.GetAsync("tests").Result;
            response.EnsureSuccessStatusCode();
            return response.Content.ReadAsAsync<IEnumerable<Test>>().Result;
        }
    }
}
