using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AutoMapper;
using Qusion.Cms.Media;
using Qusion.Cms.Media.Core;
using Qusion.Framework;
using Qusion.WebApp.Areas.Qusion.Models.Libraries;
using Qusion.WebApp.Areas.Qusion.Filters;
using Qusion.WebApp.Areas.Qusion.Models.GLibraries;
using Qusion.Cms.Modules.Media.Core;
using Qusion.Cms.Web.Http;
using Qusion.Cms.Core;
using Qusion.Cms.Core.Domain;
using Qusion.Cms.Core.Exceptions;
using Qusion.Cms.Core.Security;
using Qusion.Cms.Users.Core;
using Qusion.Cms.Users.Domain;
using Qusion.Cms.Web.Http;
using Qusion.WebApp.Areas.Qusion.Filters;
using Qusion.Framework.Configuration;
using Qusion.WebApp.Areas.Qusion.Helpers;



namespace Qusion.WebApp.Areas.Qusion.Controllers.Api
{
   [Authorize]
    public class LibraryController : ApiController
    {
        private readonly LibraryService _libraryService;
        private readonly LibraryTypeService _librarytypeService;
        private readonly UserService _userService;

        public LibraryController(LibraryService libraryService, LibraryTypeService librarytypeService, UserService userService)
        {
            _libraryService = libraryService;
            _librarytypeService = librarytypeService;
            _userService = userService;

        }

        /// <summary>
        /// Create new library and save as persistence.
        /// </summary>
        /// <param name="input">LibraryCreateInput model.</param>
        /// <returns>HttpResponseMessage with created library or bad request http status.</returns>
        [Authorize(Roles = "Administrator,Administrators,Radnik")]
        public HttpResponseMessage Create(LibraryCreateInput input)
        {
            if (input.OdjelID != null && input.LibraryTypeID != null)
            {

                LibraryType librarytype = _librarytypeService.GetById(input.LibraryTypeID);
                if (!string.IsNullOrEmpty(input.Title))
                {
                    var library = new Library
                    {
                        LibraryScope = LibraryScope.User,
                        Title = input.Title,
                        ApplicationName = "qusion/image",
                        Type = Enumeration.FromDisplayName<MediaType>(input.Type),
                        LibraryType = librarytype,
                        ArDatum = DateTime.Now

                    };
                    if (input.Status == 5)
                        library.Status = WorkflowStatus.Aktivan;
                    if (input.Status == 6)
                        library.Status = WorkflowStatus.NeAktivan;
                    else
                        library.Status = WorkflowStatus.Draft;
                    if (input.ArDatum == null)
                        library.ArDatum = DateTime.Now;
                    _libraryService.Save(library);

                    return Request.CreateResponse(HttpStatusCode.OK, Mapper.Map<Library, LibraryListModel>(library));
                }

                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            else
            {
                if (!string.IsNullOrEmpty(input.Title))
                {
                    var library = new Library
                    {
                        LibraryScope = LibraryScope.User,
                        Title = input.Title,
                        ApplicationName = "qusion/image",
                        Type = Enumeration.FromDisplayName<MediaType>(input.Type),
                        LibraryType = null,
                         ArDatum = DateTime.Now
                    };
                    if (input.Status == 5)
                        library.Status = WorkflowStatus.Aktivan;
                    if (input.Status == 6)
                        library.Status = WorkflowStatus.NeAktivan;
                    else
                        library.Status = WorkflowStatus.Draft;
                    if (input.ArDatum == null)
                        library.ArDatum = DateTime.Now;
                    _libraryService.Save(library);

                    return Request.CreateResponse(HttpStatusCode.OK, Mapper.Map<Library, LibraryListModel>(library));
                }

                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }

        /// <summary>
        /// Edit library data and save as persistance.
        /// </summary>
        /// <param name="input">LibraryEditInput model.</param>
        /// <returns>HttpResponseMessage with edited library or bad request http status.</returns>
       [Authorize(Roles = "Administrator,Administrators,Radnik")] 
       public HttpResponseMessage Edit(LibraryEditInput input)
        {
          
            if (!string.IsNullOrEmpty(input.Title))
            {
              
                var library = _libraryService.GetById(input.ID);
                library.Title = input.Title;
                library.Content = input.Content;
                if (input.LibraryTypeID != null)
                {
                    LibraryType librarytype = _librarytypeService.GetById(input.LibraryTypeID);
                    library.LibraryType = librarytype;
                }
                
                if (input.Status == 5)
                    library.Status = WorkflowStatus.Aktivan;
                if (input.Status == 6)
                    library.Status = WorkflowStatus.NeAktivan;
                else
                    library.Status = WorkflowStatus.Draft;
                if (input.ArDatum == null)
                    library.ArDatum = DateTime.Now;
                else
                    library.ArDatum = input.ArDatum;
                _libraryService.Save(library);
                return Request.CreateResponse(HttpStatusCode.OK, Mapper.Map<Library, LibraryListModel>(library));
            }
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }

        /// <summary>
        ///   Set radnik aktivan i neaktivan
        /// </summary>
        /// <param name="id"> User id. </param>
        /// <returns> Http status code 200 (Ok) or 404 (NotFound) </returns>
        [HttpGet]
        public HttpResponseMessage StatusLista(Guid id)
        {
            Library library = _libraryService.GetById(id);
            if (library.Status == WorkflowStatus.Aktivan || library.Status == WorkflowStatus.Draft)
            {
                library.Status = WorkflowStatus.NeAktivan;
                _libraryService.Save(library);
                return Request.CreateResponse(HttpStatusCode.OK, new { library.Status });
            }
            else
            {
                library.Status = WorkflowStatus.Aktivan;
                _libraryService.Save(library);
                return Request.CreateResponse(HttpStatusCode.OK, new { library.Status });
            }
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }


        [HttpGet]
        public IQueryable<LibraryListModel> All()
        {
            var list = _libraryService.GetAll();
                var model = Mapper.Map<IEnumerable<Library>, IList<LibraryListModel>>(list.ToList().Where(x => x.Title != null));
                return model.AsQueryable();
            
        }

        [HttpGet]
        public LibraryModel Get(Guid id)
        {
            var library = _libraryService.GetById(id);
                return Mapper.Map<Library, LibraryModel>(library);
            
        }

        [HttpGet]
        public IQueryable<LibraryListModel> GetByLibraryType(Guid librarytype)
        {
             var list = _libraryService.GetByLibraryType(librarytype);
                var model = Mapper.Map<IEnumerable<Library>, IList<LibraryListModel>>(list);
                return model.AsQueryable();
            
        }


        [HttpGet]
        public IQueryable<LibraryListModel> GetByType(string type)
        {
            var mediaType = Enumeration.FromDisplayName<MediaType>(type);
                var list = _libraryService.GetByType(mediaType);
                var model = Mapper.Map<IEnumerable<Library>, IList<LibraryListModel>>(list.ToList().Where(x => x.Title != null));
                return model.AsQueryable();
            
        }

        [HttpPost]
        [ModelValidationFilter]
        [Authorize(Roles = "Administrator,Administrators")]
        public HttpResponseMessage CreateType(LibraryTypeCreateModel input)
        {
            var librarytype = new LibraryType
            {
                Title = input.Title,
                Alias = input.Alias,
            };
            User owner = _userService.Current();
            // LibraryType librarytype = Mapper.Map<LibraryTypeCreateModel, LibraryType>(newLibraryType);
            librarytype.Owner = owner;
            _librarytypeService.Save(librarytype);
            return Request.CreateResponse(HttpStatusCode.OK, Mapper.Map<LibraryType, LibraryTypeModel>(librarytype));

        }

        [HttpPost]
        [ModelValidationFilter]
        [Authorize(Roles = "Administrator,Administrators")]
        public HttpResponseMessage EditType(LibraryTypeEditModel librarytype)
        {
            if (!string.IsNullOrEmpty(librarytype.Title))
            {
                var library = _librarytypeService.GetById(librarytype.ID);
                library.Title = librarytype.Title;
                library.Alias = librarytype.Alias;
                _librarytypeService.Save(library);
                return Request.CreateResponse(HttpStatusCode.OK, Mapper.Map<LibraryType, LibraryTypeListModel>(library));
            }
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }

        [HttpGet]
        public LibraryTypeModel GetType(Guid id)
        {
          LibraryType librarytype = _librarytypeService.GetById(id);
                return Mapper.Map<LibraryType, LibraryTypeModel>(librarytype);
            
        }

        [HttpGet]
        public PageResult<LibraryTypeListModel> QueryType([FromUri] LibraryTypeQueryInput input)
        {
            LibraryTypeQuery query = Mapper.Map(input, LibraryTypeQuery.Default) ?? LibraryTypeQuery.Default;
                query.Paging.PageSize = 50;
                IEnumerable<LibraryType> librarytype = _librarytypeService.Search(query);
                IList<LibraryTypeListModel> model = Mapper.Map<IList<LibraryType>, IList<LibraryTypeListModel>>(librarytype.ToList());

                return new PageResult<LibraryTypeListModel>
                {
                    Items = model,
                    Count = query.Paging.TotalCount
                };
            
        }

        [HttpGet]
        public HttpResponseMessage DeleteType(Guid id)
        {
            LibraryType librarytype = _librarytypeService.GetById(id);
            _librarytypeService.Delete(librarytype);
            return Request.CreateResponse(HttpStatusCode.OK);
        }


    }
}