﻿using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using AutoMapper;
using Castle.Core.Logging;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
using Bivi.Infrastructure.Attributes.Modularity.Plugins;
using Bivi.BackOffice.Web.Controllers.Modularity;
using Bivi.Infrastructure.Services.Depots;
using Bivi.Infrastructure.Services.Encryption;
using Bivi.Domaine;
using Bivi.BackOffice.Web.ViewModels.ViewModels;
using Bivi.BackOffice.Web.Controllers.Filters;
using Bivi.BackOffice.Web.Controllers.Helpers;
using Bivi.Infrastructure.Attributes.Modularity;

namespace Bivi.BackOffice.Web.Controllers.Modularity.Plugins
{
    [Plugin(Priority = 0)]
    public class ContextPlugin : IModularityPlugin
    {
        public void OnActionExecuting(HttpContextBase context, ActionExecutingContext filterContext, IDepotFactory depotFactory, ICryptography encryption, ILogger logger)
        {
            var controller = filterContext.Controller;

            if (context.User.Identity.IsAuthenticated)
            {
                try
                {
                    controller.ViewData["User.Login"] = context.User.Identity.Name;
                    var currentUser = depotFactory.UtilisateurDepot.GetById(Convert.ToInt64(context.User.Identity.Name));
                    controller.ViewData["User"] = Mapper.Map<Utilisateur, UtilisateurViewModel>(currentUser);
                    controller.ViewData["User.Personne"] = Mapper.Map<Personne, PersonneViewModel>(currentUser.Personne);
                }
                catch (Exception ex)
                {
                    logger.Fatal(ex.Message, ex);
                    filterContext.Result = new RedirectResult(RoutesHelper.GetUrl("LOGOUT_ACTION"));
                }
            }
        }

        public void OnActionExecuted(HttpContextBase context, ActionExecutingContext filterContext, IDepotFactory depotFactory, ICryptography encryption, ILogger logger)
        {

        }
    }
}
