using System.Linq;
using System.Net;
using System.Net.Http;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Threading.Tasks;
using System.Collections.Generic;
using Thwip.Data;
using Thwip.Data.Domain.Models;

namespace Thwip.Lookups
{
    public static class GetTimeline
    {
        [FunctionName("GetTimeline")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.User, "get", Route = "u/id/{id}/timeline")]HttpRequestMessage req, string id, TraceWriter log)
        {
            using (ThwipDb db = ThwipDb.GetDatabase("DefaultDbConnection"))
            {
                IEnumerable<Timeline> timeline = db.Timelines.Find(id);
                if (timeline.Any())
                {
                    return req.CreateResponse(HttpStatusCode.OK, new { Header = new { Id = id }, Payload = timeline });
                }
            }
            return req.CreateErrorResponse(HttpStatusCode.NotFound, $"Historical data not found.");
        }
    }
}
