﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Castle.Core.Logging;
using SOURCE.Infrastructure.Services.Depots;
using SOURCE.Infrastructure.Services.Encryption;
using SOURCE.BackOffice.Web.Controllers.Modularity;
using SOURCE.BackOffice.Web.Controllers.Helpers;
using SOURCE.Infrastructure.Constant;
using SOURCE.BackOffice.Web.Controllers.Filters;
using System.Net;
using SOURCE.BackOffice.Web.Controllers.ActionResults;
using SOURCE.Infrastructure.Extensions;
using SOURCE.Domaine.Composite;
using SOURCE.Domaine.Results;
using SOURCE.BackOffice.Web.ViewModels.ModelBuilders.Common;
using System.Text;
using System;
using System.Transactions;
using SOURCE.Infrastructure.Attributes.Modularity;
using SOURCE.BackOffice.Web.ViewModels.ModelBuilders.Administration.Personne;
using SOURCE.BackOffice.Web.ViewModels.Pages.Administration.Personne;
using SOURCE.Domaine;
using SOURCE.Infrastructure.Services.Caching;
using SOURCE.Infrastructure.Services.Exports;

namespace SOURCE.BackOffice.Web.Controllers.Administration
{
    public class PersonneController : ModularController
    {
        private readonly IPersonneModelBuilder _personneModelBuilder;

        public PersonneController(
            ILogger logger,
            ICryptography encryption,
            IDepotFactory depotFactory,
            IPersonneModelBuilder personneModelBuilder,
            ICommonModelBuilder commonModelBuilder,
            ICaching cachingService,
            IExcelExport exportService)
            : base(logger, encryption, depotFactory, commonModelBuilder, cachingService, exportService)
        {
            _personneModelBuilder = personneModelBuilder;
        }

        public ActionResult Edit(long id)
        {
            BuildActionContext(VueEnum.EditPersonne);

            var vm = _personneModelBuilder.BuildPersonneViewModel(Context, id);

            return View(vm);
        }

        public ActionResult Add()
        {
            BuildActionContext(VueEnum.EditPersonne);

            var vm = _personneModelBuilder.BuildPersonneViewModel(Context, 0);

            return View(vm);
        }

        [HttpPost]
        [ValidateModelState]
        public ActionResult Save(PersonneViewModel model)
        {
            BuildActionContext(VueEnum.EditPersonne, model.ID, model.ID > 0 ? (long)TypeActionEnum.Save : (long)TypeActionEnum.Add, null);

            var personneDto = AutoMapper.Mapper.Map<PersonneViewModel, PersonneDto>(model);

            var personne = Save(() => _depotFactory.PersonneDepot.SavePersonne(personneDto, Context.User.ID), false, true);

            var personneViewModel = AutoMapper.Mapper.Map<Personne, PersonneViewModel>(personne);

            return new JsonHttpStatusResult((int)HttpStatusCode.OK, personneViewModel);
        }
    }
}
