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

namespace SOURCE.BackOffice.Web.Controllers.Common
{

    public class TokenController : ModularController
    {
        public TokenController(
            ILogger logger,
            ICryptography encryption,
            IDepotFactory depotFactory,
            ICommonModelBuilder commonModelBuilder,
            ICaching cachingService,
            IExcelExport exportService)
            : base(logger, encryption, depotFactory, commonModelBuilder, cachingService, exportService)
        {
        }

        public ActionResult TokenRedirect(long id, int type)
        {
            //Redirection vers la page compte intervenant de l'espace candidature
            if (type == (int)TypeTokenEnum.Candidature)
            {
                var intervenant = _depotFactory.IntervenantDepot.GetById(id);
                if (intervenant == null)
                {
                    return new EmptyResult();
                }

                var token = Guid.NewGuid().ToString();
                var tokenDuration = Convert.ToInt32(ConfigurationManager.AppSettings.Get("TokenRedirectExpirationDuration"));
                var url = ConfigurationManager.AppSettings.Get("EspaceCandidature.TokenConnect.Url").Replace("{token}", token);

                _depotFactory.ServiceTokenDepot.GenerateToken(Context.User.ID, intervenant.PersonneID, DateTime.Now.AddMinutes(tokenDuration), Constants.GetStringValue(TypeTokenEnum.Candidature), token, null);


                var utilisateur = _depotFactory.UtilisateurDepot.GetById(Context.User.ID);
                if (utilisateur != null) 
                {
                    utilisateur.IsCGUAccepted = true;
                    _depotFactory.UtilisateurDepot.Update();
                }

                return Redirect(url);
            }

            return new EmptyResult();
        }

        [AuthenticationNotRequired]
        public ActionResult TokenConnect(string token)
        {
            var _token = _depotFactory.ServiceTokenDepot.GetByToken(token);

            if (_token == null || _token.DateExpiration.CompareTo(DateTime.Now) < 0)
            {
                return new EmptyResult();
            }

            var urlRedirect = string.Empty;

            FormsAuthentication.SetAuthCookie(_token.UtilisateurID.ToString(), false);

            if (_token.TypeCode.Equals(Constants.GetStringValue(TypeTokenEnum.DemandeAffectation), StringComparison.InvariantCultureIgnoreCase) && _token.IdFonctionnel.HasValue)
            {
                urlRedirect = RoutesHelper.GetUrl("DEMANDE_AFFECTATION_DETAILS", new { id = _token.IdFonctionnel.Value });
            }
            else if (_token.TypeCode.Equals(Constants.GetStringValue(TypeTokenEnum.Intervenant), StringComparison.InvariantCultureIgnoreCase) && _token.IdFonctionnel.HasValue)
            {
                urlRedirect = RoutesHelper.GetUrl("INTERVENANT", new { id = _token.IdFonctionnel.Value });
            }
            else if (_token.TypeCode.Equals(Constants.GetStringValue(TypeTokenEnum.ComparePlanning), StringComparison.InvariantCultureIgnoreCase) && _token.IdFonctionnel.HasValue)
            {
                urlRedirect = RoutesHelper.GetUrl("RECHERCHE_COMPARE_PLANNING", new { ids = _token.OptionalParam });
            }

            if (!string.IsNullOrWhiteSpace(urlRedirect))
            {
                return new RedirectResult(urlRedirect);
            }

            return new EmptyResult();
        }
    }
}
