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.Classifications;
using Qusion.Cms.Classifications.Core;
using Qusion.Cms.Web.Http;
using Qusion.WebApp.Areas.cms.Filters;
using Qusion.WebApp.Areas.cms.Models.Classifications;
using Qusion.WebApp.Areas.cms.Models.Pages;
using Qusion.WebApp.Areas.cms.Models.Validation;
using Qusion.Framework.Configuration;
using Qusion.WebApp.Areas.cms.Helpers;

namespace Qusion.WebApp.Areas.cms.Controllers
{
   // [Authorize]
    public class LabelLaktasiController : ApiController
    {
        private readonly LabelService _labelService;

        public LabelLaktasiController(LabelService labelService)
        {
            _labelService = labelService;
        }

        [HttpGet]
      [Compress]
        public PageResult<LabelListModel> Query([FromUri] LabelQueryInput input)
        {
          
                LabelQuery query = Mapper.Map(input, LabelQuery.Default) ?? LabelQuery.Default;
                IEnumerable<Label> labels = _labelService.Search(query);
                var a = labels.ToList().Where(x => x.Name != null);
                IList<LabelListModel> model = Mapper.Map<IList<Label>, IList<LabelListModel>>(a.ToList());

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

        /// <summary>
        ///   Gets list of top pages.
        /// </summary>
        /// <returns> </returns>
        [HttpGet]
      [Compress]
        public PageResult<LabelListModel> Top(string alias, Guid? parentID = null)
        {
           
                IList<Label> labels;
                if (parentID.HasValue)
                {
                    var label = _labelService.GetById(parentID.Value);
                    labels = label != null ? label.Children : new List<Label>();
                }
                else
                {
                    var tree = _labelService.GetTopLabels(alias);
                    labels = _labelService.SortByOrdinal(tree).ToList();
                }
                var a = labels.ToList().Where(x => x.Name != null);
                var model = Mapper.Map<IList<Label>, IList<LabelListModel>>(a.ToList());

                return new PageResult<LabelListModel>
                {
                    Items = model,
                    Count = labels.Count
                };
            
        }

        [HttpGet]
      [Compress]
        public HttpResponseMessage Get(Guid id)
        {
          
                Label label = _labelService.GetById(id);

                return label != null
                           ? Request.CreateResponse(HttpStatusCode.OK, Mapper.Map<Label, LabelModel>(label))
                           : Request.CreateResponse(HttpStatusCode.NotFound);
            }
        
    }
}