﻿using BookReviews.AccountsManager.DTO;
using BookReviews.Infrastructure.Commands;
using BookReviews.Infrastructure.Commands.GroupsManagment.UpdateGroupClaims;
using BookReviews.Infrastructure.Queries;
using BookReviews.Infrastructure.Queries.GetGroupClaims;
using BookReviews.UI.Site.Shared.Controllers;
using BookReviews.UI.ViewModels;
using BookReviews.UI.ViewModels.GroupsManagment.UpdateGroupClaims;
using System.Collections.Generic;
using System.Web.Mvc;

namespace BookReviews.UI.Site.GroupsManagment.UpdateGroupClaims
{
    public class UpdateGroupClaimsController : ApplicationCommandController<UpdateGroupClaimsCommand>
    {
        private ICommandHandler<UpdateGroupClaimsCommand> commandHandler = null;
        private IQueryHandler<GetGroupClaimsQuery, IList<GroupClaimItem>> queryHandler = null;

        public UpdateGroupClaimsController(
            ICommandHandler<UpdateGroupClaimsCommand> commandHandler,
            IQueryHandler<GetGroupClaimsQuery, IList<GroupClaimItem>> queryHandler,
            IMapper mapper) : base(mapper)
        {
            this.commandHandler = commandHandler;
            this.queryHandler = queryHandler;
        }

        [HttpGet]
        public ActionResult Execute(GetGroupClaimsQuery query)
        {
            //query.ClaimsForGroupWithID = 5;
            //query.Skip = 3;
            //query.Take = 5;
            //query.OrderBy = new string[] { "gdf", "fghfh" };

            UpdateGroupClaimsViewModel viewModel = new UpdateGroupClaimsViewModel();
            viewModel.GroupClaims = queryHandler.Handle(query);

            return View(viewModel);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Execute(UpdateGroupClaimsViewModel viewModel)
        {
            return CommandExecutor
                .OnErrorReturn(viewModel)
                .OnSuccess((command) => RedirectHere(command.GroupID.ToString()))
                .Execute(() => { return mapper.Map<UpdateGroupClaimsCommand>(viewModel); }, commandHandler);

            //return base.ExecuteWithSuccessAndInvalidResult(
            //    command, 
            //    commandHandler,
            //    RedirectHere(command.GroupID.ToString()),
            //    View(viewModel));
        }
    }
}