using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Results;
using WindowsDataCenter.Helpers;
using Interfaces;

namespace WindowsDataCenter
{
    [RoutePrefix("api/groups")]
    public class GroupController:ApiController
    {
        private readonly IRepository _repo;
        public GroupController(IRepository repo)
        {
            if(repo == null) throw new ArgumentNullException(nameof(repo));
            _repo = repo;
        }

        [HttpGet]
        [Route("")]
        [CacheControl(MaxAge = 0)]
        public IHttpActionResult GetGroups()
        {
            var groupList = new GroupList {Groups = _repo.GetGroups()};
            return Ok(groupList);
        }

        [HttpPost]
        [Route("create")]
        [CacheControl(MaxAge = 0)]
        public IHttpActionResult CreateGroup([FromBody] Group group)
        {
            int groupId;
            _repo.CreateGroup(group, out groupId);

            return Ok(groupId);
        }

        [HttpDelete]
        [Route("delete")]
        [CacheControl(MaxAge = 0)]
        public IHttpActionResult DeleteGroup([FromUri]int groupId)
        {
            HttpResponseMessage resp;
            var res = _repo.DeleteGroup(groupId);
            if (res == OperationResponse.DELETED)
            {
                resp = new HttpResponseMessage(HttpStatusCode.OK);
            }
            else
            {
                resp = new HttpResponseMessage(HttpStatusCode.NotFound);
            }
            return ResponseMessage(resp);
        }

        [HttpPost]
        [Route("edit")]
        [CacheControl(MaxAge = 0)]
        public IHttpActionResult UpdateGroup([FromBody] Group group)
        {
            if (group.Id == -1)
            {
                int groupId;
                _repo.CreateGroup(group, out groupId);
                group.Id = groupId;
            }
            else
            {
                _repo.UpdateGroup(group);
            }
            return Ok(group.Id);
        }
    }
}
