using Autofac;
using FluentValidation;
using GreenTree.Nachtragsmanagement.Core;
using GreenTree.Nachtragsmanagement.Core.Authentication;
using GreenTree.Nachtragsmanagement.Services.User;
using GreenTree.Nachtragsmanagement.Web.Models.Global;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GreenTree.Nachtragsmanagement.Web.Validation.Global
{
    public class PasswordChangeModelValidator : AbstractValidator<PasswordChangeDataModel>
    {
        public PasswordChangeModelValidator()
        {
            RuleFor(m => m.CurrentPassword)
                .Must(m => CurrentPasswordIsCorrect(m))
                    .WithMessage("Aktuelles Passwort ist falsch");

            RuleFor(m => m.NewPassword)
                .NotEmpty()
                    .WithMessage("Ein neues Passwort wird benötigt");

            RuleFor(m => m)
                .Must(m => m.NewPassword == m.ConfirmedPassword)
                    .WithMessage("Das neue und das bestätigte Passwort stimmen nicht überein");
        }

        private bool CurrentPasswordIsCorrect(string currentPassword)
        {
            var userHelper = Singleton<IContainer>.Instance.Resolve<IUserHelper>();
            var userService = Singleton<IContainer>.Instance.Resolve<IUserService>();

            var currentUser = userHelper.FromCookiesOrSession();

            if (currentUser == null)
                return false;

            currentUser = userService.GetUserById(currentUser.Id);

            if (currentUser == null)
                return false;

            if (currentUser.Password != StaticHelper.GetMD5Hash(currentPassword))
                return false;

            return true;
        }
    }
}