﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using SmartStoreNetCore.Core.Entities;
using SmartStoreNetCore.Core.Utilities.Interfaces;
using SmartStoreNetCore.Repositories.UnitOfWork;
using SmartStoreNetCore.Services.Interfaces;
using SmartStoreNetCore.Web.Models.ViewModels;

namespace SmartStoreNetCore.Web.ViewComponents
{
    public class SliderViewComponent : BaseViewComponent
    {
        public SliderViewComponent(ISmartStoreWorkData context, IWebService webService, IDateTimeProvider dateTimeProvider, IMapper mapper)
            : base(context, webService, dateTimeProvider, mapper)
        {
        }

        public override async Task<IViewComponentResult> InvokeAsync(object parameter)
        {
            var sliders = await this.Context.Slider.FindAsync(s => s.IsActive);
            var buttons = await this.Context.CategorySlides.GetAllAsync();

            // This should be changed. The Admin have to select which slides will be played. May be passing Id as parameter.
            var slider = sliders.FirstOrDefault();

            slider.BackgroundPictureUrl = await this.WebService.PictureServices.GetPictureUrlAsync(slider.BackgroundPictureId);

            var productSlides = await this.Context.PloductSlides
                .FindAsync(ss => ss.LanguageId == this.WebService.Language.Id && !ss.IsLimitedToStores &&ss.IsPublished);

            var categorySlides = await this.Context.CategorySlides
                .FindAsync(ss => ss.LanguageId == this.WebService.Language.Id && !ss.IsLimitedToStores && ss.IsPublished);

            foreach (var productSlid in productSlides)
            {
                productSlid.PictureUrl = await this.WebService.PictureServices.GetPictureUrlAsync(productSlid.PictureId);
            }

            foreach (var categorySlide in categorySlides)
            {
                categorySlide.PictureUrl = await this.WebService.PictureServices.GetPictureUrlAsync(categorySlide.PictureId);
            }

            var productSlidsModel = Mapper.Map<IEnumerable<ProductSlide>, IEnumerable<ProductSlideViewModel>>(productSlides);
            var categorySlidesModel = Mapper.Map<IEnumerable<CategorySlide>, IEnumerable<CategorySlideViewModel>>(categorySlides);
            
            var sliderModel = Mapper.Map<Slider, SliderViewModel>(slider);
            sliderModel.NumberOfSlides = productSlides.Count() + categorySlides.Count();
            sliderModel.ProductSlides = productSlidsModel.ToList();
            sliderModel.CategorySlides = categorySlidesModel.ToList();

            return View(sliderModel);
        }
    }
}
