using Hangfire;
using LeafWeb.WebCms.Services;
using MlkPwgen;
using Umbraco.Core;
using Umbraco.Core.Events;
using Umbraco.Core.Models;
using Umbraco.Core.Services;

namespace LeafWeb.WebCms.EventHandlers
{
    // https://our.umbraco.com/forum/umbraco-7/using-umbraco-7/64185-Assign-new-members-to-member-group-upon-registration#comment-254768
    public class MemberEvents : ApplicationEventHandler
    {
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            base.ApplicationStarted(umbracoApplication, applicationContext);
            MemberService.Created += MemberService_Created;
            MemberService.Saving += MemberService_OnSaving;
        }

        private void MemberService_OnSaving(IMemberService sender, SaveEventArgs<IMember> e)
        {
            foreach (var member in e.SavedEntities)
            {
                // Member is not approved, don't send an email at all
                if (!member.HasIdentity || !member.IsApproved)
                    continue;

                // Pull the old approval state from the member service (this is the value before the save has updated the cache)
                var alreadyApproved = ApplicationContext.Current.Services.MemberService.GetById(member.Id).IsApproved;

                //Member wasn't approved before save but is now
                if (!alreadyApproved)
                {
                    //Code to send email goes here
                }
            }
        }

        private void MemberService_Created(IMemberService sender, NewEventArgs<IMember> e)
        {
            e.Entity.IsApproved = false;
            var token = PasswordGenerator.Generate(12, allowed: "0123456789");
            e.Entity.SetValue("VerificationToken", token);
            sender.Save(e.Entity);

            // Send Email
            BackgroundJob.Enqueue<EmailNotificationService>(
                email => email.SendVerifyMemberEmail(e.Entity.Email));
        }
    }
}