using System;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using WindowsDataCenter.Helpers;
using Interfaces;

namespace WindowsDataCenter
{
    [RoutePrefix("api/users")]
    public class UsersController : ApiController
    {
        private readonly IRepository _repo;
        private readonly ILogger _logger;
        public UsersController(IRepository repo, ILogger logger)
        {
            if(logger == null) { throw new ArgumentNullException(nameof(logger));}
            _logger = logger;
            _logger.Trace("Loading Repository..");
            if(repo == null) { throw new ArgumentNullException(nameof(repo));}
            _repo = repo;
            _logger.Trace("Loaded Repository..");
        }

        [HttpGet]
        [Route("")]
        [CacheControl(MaxAge = 0)]
        public IHttpActionResult GetUsers([FromUri] string query = ""
            , [FromUri] int pageSize = -1
            , [FromUri] int pageNumber = -1
            , [FromUri] int groupId = -1)
        {
            _logger.Trace("GetUsers called with arguments >> query: {0}, pageSize: {1}, pageNumber: {2}, groupFilter: {3}", query, pageSize, pageNumber, groupId);
            
            pageNumber = pageNumber == -1 ? 1 : pageNumber;
            pageSize = GetPageSize(pageSize);
            var userList = query != string.Empty
                ? _repo.Search(query)
                : groupId != -1 
                    ? _repo.GetUsers(groupId: groupId) 
                    : _repo.GetUsers(pageNumber, pageSize);
            _logger.Trace("Got UserList from Repository, UserCount: {0}", userList.UserCount);
            if (query != string.Empty)
            {
                userList.Query = query;
                userList.PageNumber = 1;
                userList.PageSize = userList.UserCount;
            }
            else
                userList.Query = null;
            if (groupId != -1)
            {
                userList.GroupFilter = _repo.GetGroup(groupId);
            }

            userList.PageNumber = pageNumber;
            userList.PageSize = pageSize;

            _logger.Trace("Returning UserList from GetUsers.");
            var msg = Request.CreateResponse(HttpStatusCode.OK, userList);
            return ResponseMessage(msg);
        }

        private int GetPageSize(int pageSize)
        {
            var cfgPageSize = ConfigurationHandler.ConfigurationHandler.GetConfiguration("DefaultPageSize")?? 10.ToString();

            return pageSize == -1
                ? Convert.ToInt32(cfgPageSize)
                : pageSize;
        }

        [HttpGet]
        [Route("{id:int}")]
        [CacheControl(MaxAge = 0)]
        public IHttpActionResult GetUserDetails(int id)
        {
            _logger.Trace("Getting details for user id: {0}", id);
            var ret = _repo.GetUser(id);

            _logger.Trace("Got details for user id: {0}, name: {1}", id, ret.FirstName);

            var resp = Request.CreateResponse(HttpStatusCode.OK, ret);
            return ResponseMessage(resp);
        }

        [HttpPost]
        [Route("create")]
        [CacheControl(MaxAge = 0)]
        public IHttpActionResult CreateUser([FromBody] User user)
        {
            int userId;
            _repo.UpdateUser(user, out userId);
            //TODO return ID.
            return ResponseMessage(new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent("unknownIdTODO")});
        }

        [HttpPost]
        [Route("edit")]
        [CacheControl(MaxAge = 0)]
        public IHttpActionResult EditUser([FromBody] User user)
        {
            _logger.Trace("Editing user, id: {0}", user.UserId);
            int userId;
            _repo.UpdateUser(user, out userId);

            _logger.Trace("Edited details for user id: {0}", user.UserId);
            var resp = Request.CreateResponse(HttpStatusCode.OK, userId);
            return ResponseMessage(resp);
        }
    }
}