using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using System.Net.Http;

namespace ConferenceBuddyLib
{
    public class JsonEventsRepository
    {
        /// <summary>
        /// Parses a string of JSON into a List of Event objects
        /// </summary>
        /// <param name="json">JSON data to be parsed</param>
        /// <returns>List of Event objects</returns>
        public List<Event> LoadFromJson(string json)
        {
            return JsonConvert.DeserializeObject(json, typeof(List<Event>)) as List<Event>;
        }

        /// <summary>
        /// Reads a file located at specific path and parses the text into a List of Event
        /// </summary>
        /// <param name="path">Path to the file</param>
        /// <returns>List of Event objects</returns>
        public List<Event> LoadJsonFromFile(string path)
        {
            string json = System.IO.File.ReadAllText(path);
            return LoadFromJson(json);
        }

        /// <summary>
        /// Read JSON data from a WebAPI endpoint and parse it into a List of Event
        /// </summary>
        /// <param name="uri">Uri of the WebAPI service</param>
        /// <returns>List of Event objects</returns>
        public List<Event> LoadJsonFromWebApi(string uri)
        {
           HttpClient apiClient = new HttpClient();
           HttpResponseMessage response = apiClient.GetAsync(uri).Result;
           List<Event> events = LoadFromJson(response.Content.ReadAsStringAsync().Result);
           return events;
        }
    }
}
