/*-
 * ~~~~~~licensing~~~~~~
 * basic-auth-impl
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.system.auth.basic.jpa.listener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;

public class EntityEventListenerRegistry {

    private static final Log LOG = LogFactory.getLog(EntityEventListenerRegistry.class);
    private static final int SESSION_WAIT_TIMEOUT = 50000;

    private SessionFactory sessionFactory;
    private BasicAuthPostEventListener basicAuthPostEventListener;
    private int initLimiter = 0;


    public void registerListeners() {
        LOG.info("Init EntityEventListenerRegistry " + sessionFactory.getClass().getName());

        EventListenerRegistry registry = prepareRegistry();
        registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(basicAuthPostEventListener);
        registry.getEventListenerGroup(EventType.POST_COMMIT_UPDATE).appendListener(basicAuthPostEventListener);
        registry.getEventListenerGroup(EventType.POST_COMMIT_DELETE).appendListener(basicAuthPostEventListener);
    }

    private EventListenerRegistry prepareRegistry() {
        try {
            SessionFactoryImplementor sessionFactoryImpl = sessionFactory.unwrap(SessionFactoryImplementor.class);
            EventListenerRegistry registry = sessionFactoryImpl.getServiceRegistry().getService(EventListenerRegistry.class);
            return registry;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            if (initLimiter == 10) {
                LOG.error(e);
            }
            try {
                LOG.warn("Wait sessionFactory initialization...");
                Thread.sleep(SESSION_WAIT_TIMEOUT);
            } catch (InterruptedException e1) {
            }

        }
        return initLimiter++ <= 9
                ? prepareRegistry()
                : null;
    }


    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public BasicAuthPostEventListener getBasicAuthPostEventListener() {
        return basicAuthPostEventListener;
    }

    public void setBasicAuthPostEventListener(BasicAuthPostEventListener basicAuthPostEventListener) {
        this.basicAuthPostEventListener = basicAuthPostEventListener;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

}
