﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Raven.Client;
using Sisyphus.Queue.Data;
using Sisyphus.Queue.Data.Dto;
using Sisyphus.Queue.Infrastructure.AutoMapper;

namespace Sisyphus.Queue.Controller
{
    public class QueuesController : ApiController
    {
        private readonly IDocumentSession _documentSession;

        public QueuesController(IDocumentSession documentSession)
        {
            _documentSession = documentSession;
        }

        public List<QueueDTO> Get()
        {
            var queues = _documentSession.Query<Data.Queue>().ToList();

            var queueDtos = queues.MapTo<List<QueueDTO>>();

            return queueDtos;
        }

        public HttpResponseMessage Post(HttpRequestMessage<QueueDTO> request, QueueDTO taskDto)
        {
            var response = new HttpResponseMessage();
            var input = taskDto;

            if (input == null)
            {
                response.StatusCode = HttpStatusCode.BadRequest;
                response.ReasonPhrase = "No data provided";

                return response;
            }

            var queue = input.MapTo<Data.Queue>();

            _documentSession.Store(queue);
            _documentSession.SaveChanges();

            response.StatusCode = HttpStatusCode.Created;

            string uri = Url.Route("DefaultApi", new { id = queue.Id });
            response.Headers.Location = new Uri(Request.RequestUri, uri);

            return response;
        }
    }
}