package ca.firstvoices.workers;

import ca.firstvoices.utils.FVRegistrationMailUtilities;
import ca.firstvoices.utils.FVRegistrationUtilities;
import org.nuxeo.ecm.core.api.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.core.work.AbstractWork;
import org.nuxeo.runtime.api.Framework;
import javax.security.auth.login.LoginContext;
import java.util.Calendar;

import static ca.firstvoices.operations.FVGetPendingUserRegistrations.APPROVED;
import static ca.firstvoices.utils.FVRegistrationConstants.*;


/**
 *
 */
public class FVRegistrationTimeOutWorker extends AbstractWork {


        private static final Log log = LogFactory.getLog(FVRegistrationTimeOutWorker.class);

        public static final String CATEGORY_CHECK_REGISTRATION_TIMEOUT = "checkEditLocks";

        @Override
        public String getCategory() {
            return CATEGORY_CHECK_REGISTRATION_TIMEOUT;
        }

        @Override
        public String getTitle() {
            return "Check user registration timeout.";
        }

        public FVRegistrationTimeOutWorker() {
            super("check-registration-timeout");
        }


        private int checkRegistrationTimeOut( Calendar dateRegistered )
        {
            long diffDays = FVRegistrationUtilities.calculateRegistrationAgeInDays( dateRegistered );
            long modHours = FVRegistrationUtilities.calculateRegistrationModHours( dateRegistered );

            int actionValue = 0;

            // currently set to check at 2am, 10am, 6pm
            if( diffDays == REGISTRATION_DELETION_IN_DAYS && modHours < 8)         actionValue = REGISTRATION_DELETION_ACT;
            else if( diffDays == REGISTRATION_EXPIRATION_IN_DAYS && modHours < 8)  actionValue = REGISTRATION_EXPIRATION_ACT;
            else if( diffDays == MID_REGISTRATION_PERIOD_IN_DAYS && modHours < 8)  actionValue = MID_REGISTRATION_PERIOD_ACT;

            return actionValue;
        }

        @Override
        public void work()
        {
            LoginContext lctx = null;
            CoreSession s = null;
            FVRegistrationMailUtilities mailUtil = new FVRegistrationMailUtilities();

            try
            {
                lctx = Framework.login(); // system login
                s = CoreInstance.openCoreSession("default");

                DocumentModelList registrations = s.query(String.format("Select * from Document where ecm:mixinType = 'UserRegistration'"));

                for (DocumentModel uReg : registrations)
                {
                    Calendar regCreated = (Calendar) uReg.getPropertyValue("dc:created");

                    int regTOType = checkRegistrationTimeOut( regCreated );

                    // regTOType
                    //
                    // 0 - no action required (either already dealt with or still within no-action period)
                    //
                    // MID_REGISTRATION_PERIOD_ACT - registration is closing on timeout
                    //                               an email needs to be sent to a user who started registration
                    //                               and email informing LanguageAdministrator that user registration will be deleted in ? days
                    //
                    // REGISTRATION_EXPIRATION_ACT - registration timed out and it will be deleted in 24 hrs - last chance to activate account
                    //                               send an email to originator of registration request with information about cancellation
                    //
                    // REGISTRATION_DELETION_ACT -   registration should be deleted
                    //

                    // if registration has lifecycle set to accepted user already provided password
                    // and registration is just a reminder of the registration operation
                    if( uReg.getCurrentLifeCycleState().equals(APPROVED) )
                    {
                        mailUtil.emailReminder(regTOType, uReg, s);
                    }

                    if( regTOType == REGISTRATION_DELETION_ACT )
                    {
                        log.info( "Registration period expired for user" + uReg.getPropertyValue("userinfo:firstName") + " " + uReg.getPropertyValue("userinfo:lastName") + ". Registration was deleted");
                        s.removeDocument( uReg.getRef() );
                    }
                 }

                 s.save();

            } catch (Exception e) {
               log.warn(e);
            }
            finally {
               if( s != null ) s.close();
                try
                {
                    if( lctx!= null) lctx.logout();
                }
                catch( Exception e)
                {
                    log.warn(e);
                }
            }
        }

    }

@@ -2393,89 +2393,94 @@
 ery(
-String.format(%22Select * from Document where ecm:mixinType = 'UserRegistration
+%22SELECT * FROM FVUserRegistration WHERE ecm:currentLifeCycleState = '%22+ APPROVED +%22
 '%22)
-)
 ;%0A%0A 
@@ -3715,155 +3715,94 @@
     
-// if registration has lifecycle set to accepted user already provided password%0A                    // and registration is just a reminder of the r
+switch (regTOType) %7B%0A                        // TODO: Add to Audit log =%3E log.info( %22R
 egis
@@ -3813,180 +3813,280 @@
 ion 
-o
 per
-ation%0A                    if( uReg.getCurrentLifeCycleState().equals(APPROVED) )%0A                    %7B%0A                        mailUtil.emailReminder(regTOType, uReg, s
+iod expired for user%22 + uReg.getPropertyValue(%22userinfo:firstName%22) + %22 %22 + uReg.getPropertyValue(%22userinfo:lastName%22) + %22. Registration was deleted.%22);%0A                        case REGISTRATION_DELETION_ACT:%0A                            s.removeDocument( uReg.getRef() 
 );%0A 
@@ -4096,33 +4096,42 @@
                 
-%7D
+    break;
 %0A%0A              
@@ -4140,25 +4140,21 @@
     
-if( regTOType == 
+    case MID_
 REGI
@@ -4166,22 +4166,19 @@
 ION_
-DELETION
+PERIOD
 _ACT
- )
+:
 %0A   
@@ -4198,270 +4198,147 @@
     
-%7B%0A
     
-                    log.info( %22Registration period expired for user%22 + uReg.getPropertyValue(%22userinfo:firstName%22) + %22 %22 + uReg.getPropertyValue(%22userinfo:lastName%22) + %22. Registration was deleted%22);%0A                        s.removeDocument( uReg.getRef() )
+case REGISTRATION_EXPIRATION_ACT:%0A                            mailUtil.emailReminder(regTOType, uReg, s);%0A                        break
 ;%0A  

Clean up and select the correct reg type (avoid NPE)