using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using WindowsDataCenter.Helpers;
using Interfaces;
using Newtonsoft.Json;

namespace WindowsDataCenter
{
    [RoutePrefix("api/timelogs")]
    public class TimelogController: ApiController
    {
        private readonly IRepository _repo;
        private readonly ILogger _logger;

        public TimelogController(IRepository repo, ILogger logger)
        {
            if (repo == null)
            {
                throw new ArgumentNullException(nameof(repo));
            }
            _repo = repo;
            if(logger == null) throw new ArgumentNullException(nameof(logger));
            _logger = logger;
        }

        [Route("")]
        [CacheControl(MaxAge = 0)]
        public IHttpActionResult GetTimeLogs([FromUri]int userId, [FromUri] DateTime? selectedDate = null)
        {
            _logger.Trace("Getting Time Logs for user with id: {0}, for the calendar week that the date {1} belongs to.", userId, selectedDate ?? DateTime.UtcNow.Date);
            TimeLogList logList;

            if (selectedDate == null)
                logList = _repo.GetTimeLogs(userId);
            else
                logList = _repo.GetTimeLogs(userId, selectedDate.Value);

            _logger.Trace("Got Time logs for the user: {0}, returned {1} records", userId, logList.TimeLogCount);

            var msg = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(JsonConvert.SerializeObject(logList), Encoding.UTF8, "application/json")
            };
            return ResponseMessage(msg);
        }
    }
}
