using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AutoMapper;
using Qusion.Cms.Classifications.Core;
using Qusion.Cms.Media;
using Qusion.Cms.Media.Core;
using Qusion.Cms.Media.Images;
using Qusion.WebApp.Areas.Qusion.Filters;
using Qusion.WebApp.Areas.Qusion.Models.Images;
using Qusion.WebApp.Areas.Qusion.Models.Libraries;
using Ranslant.JSON.Linq;
using System.Security.Policy;
using System.Web;
using Qusion.Framework.Configuration;
using Qusion.WebApp.Areas.Qusion.Helpers;



namespace Qusion.WebApp.Areas.Qusion.Controllers.Api
{
    public class ImageController : ApiController 
    {
        private readonly ImageService _imageService;
        private readonly LabelService _labelService;
        private readonly LibraryService _libraryService;

       
        public ImageController(ImageService imageService, LibraryService libraryService, LabelService labelService)
        {
            _imageService = imageService;
            _libraryService = libraryService;
            _labelService = labelService;
        }

        [HttpGet]
        public ImageModel Get(Guid id)
        {

            ImageItem image = _imageService.GetById(id);
            return Mapper.Map<ImageItem, ImageModel>(image);

        }
     
        [HttpGet]
        public HttpResponseMessage eQuery([FromUri] ImageQueryInput input)
        {
            
                ImageQuery query = Mapper.Map<ImageQueryInput, ImageQuery>(input);

                query.Paging.PageSize = 20;
                Library library = input.LibraryID.HasValue ? _libraryService.GetById(input.LibraryID) : null;
                string some = _imageService.Settings.CachePath;
                string type = "eImage";
                IList<ImageItem> images = _imageService.Search(query).ToList();
                var a =  images.Where(x => x.Library.Type.Name == type);
                a.ToList();
                var model = new ImageListWrapper
                {
                    Library = Mapper.Map<Library, LibraryListModel>(library),
                    Images = Mapper.Map<IEnumerable<ImageItem>, IList<ImageListModel>>(a),
                    Paging = query.Paging
                };

                return Request.CreateResponse(HttpStatusCode.OK, model);
            
            
        }

        [HttpGet]
        public HttpResponseMessage Query([FromUri] ImageQueryInput input)
        {
            
            ImageQuery query = Mapper.Map<ImageQueryInput, ImageQuery>(input);

            query.Paging.PageSize = 20;
            Library library = input.LibraryID.HasValue ? _libraryService.GetById(input.LibraryID) : null;
            string some = _imageService.Settings.CachePath;
            string type = "Image";
            IList<ImageItem> images = _imageService.Search(query).ToList();
            var a = images.Where(x => x.Library.Type.Name == type);
            a.ToList();
            var model = new ImageListWrapper
            {
                Library = Mapper.Map<Library, LibraryListModel>(library),
                Images = Mapper.Map<IEnumerable<ImageItem>, IList<ImageListModel>>(a),
                Paging = query.Paging
            };

            return Request.CreateResponse(HttpStatusCode.OK, model);


        }

        /// <summary>
        /// Permanently delete library and all images in it.
        /// </summary>
        /// <param name="id"> Id of library. </param>
        /// <returns> </returns>
        [HttpGet]
        public HttpResponseMessage RemoveLibrary(Guid id)
        {
            Library library = _libraryService.GetById(id);
            IList<ImageItem> images = _imageService.GetForLibrary(id);
          
            var errors = new Dictionary<string, string[]>();

            if (errors.Count == 0)
            {
                try
                {
                    if (images.Count == 0)
                    {
                        _libraryService.DeleteDirectory(library);
                        _libraryService.Delete(library);
                        return Request.CreateResponse(HttpStatusCode.OK);
                    }
                    else
                    {
                        foreach (ImageItem item in images)
                        {
                            _imageService.DeleteFile(_imageService.GetById(item.GuidID));
                            _imageService.Delete(_imageService.GetById(item.GuidID));
                        }
                        _libraryService.DeleteDirectory(library);
                        _libraryService.Delete(library);
                        WriteJson();
                        return Request.CreateResponse(HttpStatusCode.OK);
                     
                    }
               
                }
                catch (Exception)
                {
                    errors.Add("removeError", new[] { "images.not_possible_delete_gallery" });
                }
           
            }
            return Request.CreateResponse(HttpStatusCode.OK, new { Errors = errors });
        }


        /// <summary>
        ///   Remove image item.
        /// </summary>
        /// <param name="id"> Id of image item. </param>
        /// <param name="permanently"> Status for delteting image from file system. </param>
        /// <returns> </returns>
        [HttpGet]
        public HttpResponseMessage Remove(Guid id, bool permanently = false)
        {
            var errors = new Dictionary<string, string[]>();
            if (errors.Count == 0)
            {
                try
                {
                    _imageService.Delete(_imageService.GetById(id), permanently);
                
                    return Request.CreateResponse(HttpStatusCode.OK);
                }
                catch (Exception e)
                {

                    errors.Add("removeImageError", new[] {"images.not_possible_delete_image"});
                }
            }
            return Request.CreateResponse(HttpStatusCode.OK, new { Errors = errors });
        }

        /// <summary>
        /// Reordering images in library.
        /// </summary>
        /// <param name="input">Input properties.</param>
        /// <returns>Http status ok.</returns>
        [HttpPost]
        public HttpResponseMessage Organize(OrganizeInput input)
        {
            _imageService.Organize(input.Members);
            return Request.CreateResponse(HttpStatusCode.OK);
        }

        [HttpGet]
        public HttpResponseMessage Settings()
        {
            ImageSettings settings = _imageService.Settings;
            ImageSettingsModel model = Mapper.Map<ImageSettings, ImageSettingsModel>(settings);
            return Request.CreateResponse(HttpStatusCode.OK, model);
        }

        [HttpPost]
        [ModelValidationFilter]
        public HttpResponseMessage Settings(ImageSettingsInput model)
        {
            ImageSettings settings = _imageService.Settings;

            settings.AllowedExtensions = settings.AllowedExtensions.Replace(" ", "");
            Mapper.Map(model, settings);
            _imageService.Settings.Save();
            ImageSettingsModel response = Mapper.Map<ImageSettings, ImageSettingsModel>(settings);
            return Request.CreateResponse(HttpStatusCode.OK, response);
        }

        [HttpGet]
        public HttpResponseMessage RemoveSettings()
        {
            _imageService.Settings.Delete();
            return Request.CreateResponse(HttpStatusCode.OK);
        }

        public JDocument WriteJson()
        {

            var putanja = System.Web.HttpContext.Current.Server.MapPath("~/Areas/Qusion/Scripts/App/images/json/data.json");
            if (putanja != null)
            {
                if (putanja.Length == 0)
                    return null;
                IEnumerable<ImageItem> images = _imageService.GetAll();

                JDocument doc = new JDocument();
                foreach (ImageItem ii in images)
                {
                    JObject jsonimage = new JObject(
                                     new JObjectMember("thumb", new JString("../../_content/_media/" + ii.Library.ID + "/" + ii.FileName)),
                                     new JObjectMember("image", new JString("../../_content/_media/" + ii.Library.ID + "/" + ii.FileName)),
                                     new JObjectMember("title", new JString(ii.Title)),
                                     new JObjectMember("folder", new JString(ii.Library.Title))
                     );

                    doc.Add(ii.GuidID.ToString(), jsonimage);
                }
                var url = Path.Combine(putanja);
                doc.Save(url);
                return doc;
            }
            return null;
          
        }
    }
}